"this" keyword in JS - I'm confused
I am confused about the key this
in JS as shown below. Why is this.this_
undefined on line 3)? Any simple exalain for this? On line 2) this
points to a Window object - I was surprised, but this is acceptable to me - why? The only thing that works for me is using a variable this2_
, but I think this is not graceful. How to use this
in a nice, elegant approach that always works and points to an object O
?
var a = function(callback){
callback('test');
};
var O = function(){
this.val = 'abc';
var this2_ = this;
this.this_ = this;
this.f = function(){
console.log(this); // (1) this -> O object, that OK
a(function(){
console.log(this); // (2) this -> Window object
console.log(this.this_); // (3) this.this_ -> undefined
console.log(this2_); // (4) this2_ -> O object
});
}
};
var o = new O();
o.f();
source to share
It is not recommended to "manage" this
because it will change in different areas. In this case, when you try to get the value in the new function, you are in the new scope and the this
window object is being referenced.
you should use a new variable and try not to attach things to this
. Just use it read-only.
NOTE. It is not possible to do this (e.g. jQuery does a great job with it this
) but is not recommended.
So, in your case, you can do something like this:
var O = function(){
var this2;
this2.this_ = this;
this2.val = 'abc';
this.f = function(){
a(function(){
console.log(this2.val); // (1) 'abc'
console.log(this2.this_); // (2) O object
});
}
};
source to share