What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Each function has its own execution context, the this
keyword retrieves the value of the current context.
The doStuff
identifier and the obj.myMethod
property refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();
), the this
value inside that function, will refer to obj
.
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 this
value of that callback.
Does myThis contain a copy of this or a reference to it?
The myThis
identifier will contain a reference to the object that is also referenced by the this
value on the outer scope.
Is it generally not a good idea to use this in closures?
If you understand how the this
value is handled implicitly, I don't see any problem...
Since you are using jQuery, you might want to check the jQuery.proxy
method, is an utility method that can be used to preserve the context of a function, for example:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
$.get('http://example.com', jQuery.proxy(function(){
alert(this.myHello);
}, this)); // we are binding the outer this value as the this value inside
}
var obj = new myObject;
obj.myMethod();
See also:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…