What is this in JavaScript?

What is this in JavaScript? We will try to answer in our own words:
This – is a reference to the current object, in which it is mentioned;
This – is a reference to the object mentioned before the point in property or method;
This – is a reference to the new object created by the constructor (class).

Let’s look at the example of a constructor that creates a new object, adding methods in it:

"use strict"
function Machine(power) {
	this.power = power;
	this.hi = function () {alert("result for THIS: " + this.power)}; // (1)
	var self = this; 
	function priv() {alert ("result for SELF: " + self.power)}; // (2)
	this.hello = function () {
var machine = new Machine(10);

Machine is a constructor that creates an object and adds a reference to it in the variable machine. The method hi displays a message with the value of the property power in the line (1).

The power property and hi method have the same this – a reference to the new object, which will be created by constructor Machine.

Everything is clear here, therefore let`s looks at the line (2): we specified self.power instead of this.power in the priv() function. What for?

In fact at the time of priv() function initialization in the lines (2) its this value is not defined (for “use strict” mode) or it`s equal window (without “use strict”) and it is also undefined! To this end, we deliberately created a variable self and recorded in it the reference to the current object which will be created by constructor. Now everything is OK – function priv() displays the value of the power in the required context.

Of course, instead of used self, we could use the methods of call / apply / bind for strict binding of context, for example (this). However, using of self is more simple solution!

Cookies | Privacy Policy | Terms and ConditionsSoftSprint ©