📜 ⬆️ ⬇️

Something about using this

Good day, gentlemen!

There are a lot of interesting nuances in javascript that can hardly be found in other programming languages. Consider the most necessary, in my opinion, of them - this.
This post will help refresh knowledge on this topic.
I will not explain the theory for a long time, it is better to go straight to the code and think about what will happen as a result of its implementation.

This in different contexts
var firstObject = { value: 0, increment: function () { this.value++ ; console.log(this.value); } }; firstObject.increment(); 


What do we see in the console?
One, because in this context, this points to firstObject, since the increment function is a method of the firstObject object.
')
 var secondObject = { value: 0 }; secondObject.increment = function () { var incrementInternal = function () { this.value++ ; console.log(this.value); } incrementInternal(); } secondObject.increment(); 


In this case, alas, there will be no miracle, and the value will not be more than one.
IncrementInternal is a function that is called in the context of the increment method, and in javascript it is not a sufficient condition to bind this to the secondObject object.

HINT: This behavior is often bypassed in a similar way by keeping a reference to this:
 var secondObject = { value: 0 }; secondObject.increment = function () { var self = this; var incrementInternal = function () { self.value++ ; console.log(self.value); } incrementInternal(); } secondObject.increment(); 


The following example is quite simple.
 var thirdObject = function (value) { this.value = value; this.increment = function () { this.value++ ; console.log(this.value); } } var thObj = new thirdObject(0); thObj.increment(); 


Of course, there will be one again in the console, because when you call the operator, this this will point to the current object.
Javascript experts have accurately noticed how to improve the code by making one small change.
 var thirdObject = function (value) { this.value = value; } thirdObject.prototype.increment = function () { this.value++ ; console.log(this.value); } var thObj = new thirdObject(0); thObj.increment(); 

Thus, you can significantly improve performance if you need to create many instances of the thirdObject object, since the increment method will not be created for every new thirdObject object, it will be available at the prototype level.

It is important to remember that you can change the value of this using call and apply, so there is a certain danger in using this. Use javascript features wisely to avoid unpleasant situations.

Source: https://habr.com/ru/post/178265/


All Articles