I hope that I understand your question right . because the way you put it is a bit of mind-f*** XD .
but from what i understood . im going to answer your question as in "what do we use the that
trick for ? ".
So here is a perfectly healthy object .
var myobject = {
firstMethod : function(){
this.secoundMethod(); // calls the other method
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
and now i want to do some jquery magic (or any other thing that has a call back function) .
im going to use jQuery but feel free to do other things .
var myobject = {
firstMethod : function(){
var _this = this ;
this.secoundMethod(); // calls the other method
$('.myClass').animate({'width':300} , 300 , function(){
// this is a call back functon which will be called as soon as the animation ends
// the problem is that if i call @var : `this` , it wont work because im in
// another scope other than the firstMethod .
// so the following will throw an error .
this.secoundMethod(); // error
// to solve this you need the @var : `that` , or in my case i love it to be _this
_this.scoundMethod() // this will work .
})
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
So mainly _this
(in my case) is used to scope things . so I can access the object scope inside other scope .
to be honest i have used this trick in other places (in like 99% of cases);
even the 1% that is left is basically the same idea but with much deeper nesting or with lots of closures and stuff like that.
How dangerous can this be ?!
Well it depends on how smart you are . here is another brain example
var myobject = {
firstMethod : function(){
var _this = this ,
someObject : {
firstMethod : function(){
this.scoundMethod(); // if you log this you will get 'the wrong method'.
_this.scoundMethod(); // in here you get 'hi from method 2'.
},
scoundMethod : function(){
return 'the wrong method';
}
};
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
As you can see this is dangerous not because it doesn't work , but the fear id that it works . because if you have similarly named functions and you have a missed-up scope you end up with hours and hours of digging . While if you dont have that .. you will get just a nice error which you can fix right away
How long can this go .
will you can nest as much as you like . but there are consequences (rarely huh?!).
enjoy the following and dont ever attempt that at home .
var myobject = {
firstMethod : function(){
var _this = this ,
someVar = [1 , 2 , 3 ] ;
this.scoundMethod(function(){
var that = this;
$.each(someVar,function(elementName){
var them = this;
$('.'+elementName).animate({} , 300 , function(){
console.log(them) // logs the element
console.log(_this.scoundMethod()) // logs 'hi from method 2'
})
})
}
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
Other resources :
Hope I have made it simple . And that I didn't answer the wrong question .