A bit 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 these - this.
This post will help to refresh knowledge on this topic.
I will not explain the theory for a long time, it’s 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 will we see in the console?
One, because in this context, this points to firstObject, since the increment function is a method of the firstObject.

var secondObject = {
	value: 0
};
secondObject.increment = function () {
	var incrementInternal = function () {
		this.value++ ;
		console.log(this.value);
	}
	incrementInternal();
}
secondObject.increment();


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

HINT: This behavior is often circumvented in a similar way, retaining a link 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 pretty 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, in the console there will again be one, because when the new operator is called, this will point to the current object.
Javascript experts have definitely noticed how you can 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 each new thirdObject, 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.

Also popular now: