+ 1

What "this" refers to inside a constructor function ?

Ex: function obj() { _this = this; } var a = new obj(); console.log(a == _this) // true In this example, i'm not sure if i understand why it logs true. Correct me if i'm wrong : First, we define a constructor function which is our object blueprint. Then, to create the object we instantiate the constructor function by using the new operator. Now how can _this be accessible outside the constructor function ? Is it because _this refers to this which points to the "a" object ?

12th Apr 2019, 7:10 PM
codeKameleon
codeKameleon - avatar
5 Antworten
+ 2
codeKameleon exactly! Here _this is storing this, which is the reference to the current instance of an object. And hence when you create an instance of the class and storing its reference to 'a', it's the same reference as 'this'. You can create as many instances as you want, all of them will give true for instance == _this but comparing 2 different instances like a and b will give false.
12th Apr 2019, 7:16 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 4
You should always use var to prevent any confusion as _this is global and is an assignment rather then a declaration. Also this refers to the window object yes 👍
12th Apr 2019, 7:58 PM
D_Stark
D_Stark - avatar
+ 2
M. Watney Ok i see ! Thank you👌 But when you say all instance of the class == this will give true, you mean ==_this, right ? because _this refers to the "a" object but this will refer to the Window object ?
12th Apr 2019, 7:30 PM
codeKameleon
codeKameleon - avatar
+ 2
codeKameleon yes _this. I edited that.
13th Apr 2019, 12:26 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
D_Stark Thanks
12th Apr 2019, 8:00 PM
codeKameleon
codeKameleon - avatar