3

I'm confused about this keyword in JS like below. Why this.this_ is undefined in line 3) ? Any simple exalain for that ? In line 2) this points to Window object - i was suprised, but it is acceptable for me - why is that ? The only working for me is to use this2_ variable, but i think that is not elegant. How to use this in good,elegant approach to always work and points to O object ?

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's 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();
marioosh
  • 27,328
  • 49
  • 143
  • 192
  • Why would you want to do that? Why because `this` is not `this` inside that function. Your comments show that. – epascarello Aug 04 '14 at 13:12
  • 1
    `var this2_ = this;` is the way to do this. the reason is the scope changes within another function and `this` becomes something different. with `var this2_ = this` you are putting it into a local var that is within scope of the inner function. – Smern Aug 04 '14 at 13:13
  • Here's an explanation of 'this': https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this. – Kwebble Aug 04 '14 at 13:18

1 Answers1

3

It is not recommended to "manage" the this, because it will change on different scopes. In this case, when you try to get the value in a new function, you are in a new scope, and the this refers to the window object.

you should use a new variable and try not to attach things to the this. Just use it for read-only reasons

NOTE: It is not impossible to do this (for example jQuery does a very good manage of the this) but it is not recommended.

So in your case, you could 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
        });
    }
};
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
  • Thank You. I'm staying with `var this_ = this;` as the first line of code in object and using `this_` to access object instance in "all places". This is the easiest way i think. – marioosh Aug 05 '14 at 08:29