I’m a beginner to closures (and Javscript in general), and I can’t find a satisfactory explanation as to what’s going on in this code:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
var myThis = this;
$.get('http://example.com', function(){
alert(this.myHello);
alert(myThis.myHello);
});
}
var obj = new myObject;
obj.myMethod();
It will alert ‘undefined’ and then ‘hello’. Obviously this should not be jQuery specific, but this is the simplest form of my original code I could come up with. The closure in do_stuff() has access to the variables in that scope, but apparently this rule does not apply to the this keyword.
Questions:
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())? Does myThis contain a copy of this or a reference to it? Is it generally not a good idea to use this in closures?
Any response much appreciated.
Each function has its own execution context, the
thiskeyword retrieves the value of the current context.The
doStuffidentifier and theobj.myMethodproperty refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();), thethisvalue inside that function, will refer toobj.When the Ajax request has succeeded, jQuery will invoke the second function (starting a new execution context), and it will use an object that contains the settings used for the request as the
thisvalue of that callback.The
myThisidentifier will contain a reference to the object that is also referenced by thethisvalue on the outer scope.If you understand how the
thisvalue is handled implicitly, I don’t see any problem…Since you are using jQuery, you might want to check the
jQuery.proxymethod, is an utility method that can be used to preserve the context of a function, for example:See also: