softsprint menu Order

What is this in JavaScript?

January 18, 2017 in 1:44 pm | wiki

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
"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 () {
		priv()
	};   
}; 
var machine = new Machine(10);
machine.hi();
machine.hello();

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 priv.call (this). However, using of self is more simple solution!

Let`s discuss

softsprint heart

Our contacts

Lviv, Ukraine
моб: +380 97 551 44 55
skype: softsprint.net

Say hello!