In jQuery, how do you resolve the scope of "this", when you are in the scope of each()?
I've created an Object, and have a method setup() in the object.
this.debug = function (){...}
this.setup = function(){
开发者_StackOverflow中文版 var fieldsets = form.children("fieldset");
fieldsets.each(function(){
this.debug($(this).attr("class")));
});
}
I'm trying to call this.debug which is in the scope of the Object but not in the scope of each, since THIS is a different this...
How do I access this.debug?
Say var that = this
after this.debug, then do that.debug
.
This is basically Skilldrik's answer, but showing you where it works best
this.setup = function(){
// save it in a scoped var... some people use "self" for this purpose, i prefer
// naming it whatever the outer object actually is...
var containingObject = this;
var fieldsets = form.children("fieldset");
fieldsets.each(function(){
// use that scoped var later!
containingObject.debug($(this).attr("class")));
});
}
In jQuery 1.4 you can do:
this.debug = function (){...}
this.setup = function(){
var fieldsets = form.children("fieldset");
fieldsets.each(jQuery.proxy(function(){
this.debug($(this).attr("class")));
},this);
}
The jQuery.proxy(function, object) function will take 2 arguments:
- The function will be the function used in the loop.
- The object argument will be the
this
object inside the function.
In this way, you can transfer the this
from the outer scope inside the each
function.
I tried this in my Greasemonkey-Console:
this.debug = function() {
console.log("foo");
};
this.setup = function() {
var fieldsets = form.children("fieldset");
fieldsets.each(function(){
debug($(this).attr("class"));
});
};
Which will search the scope for any debug .. which that is hopefully the function above. This will fail, if you assign a variable with the very same name :)
I normally do it this way: (note:example below is from memory but looks sound):
function CustomObject()
{
var _instance = this;
this.debug = function(){...};
this.setup =
function()
{
var fieldsets = form.children("fieldset");
fieldsets.each(
function()
{
_instance.debug($(this).attr("class"));
});
};
}
this.debug = function (){...}
this.setup = function(){
var that = this;
var fieldsets = form.children("fieldset");
fieldsets.each(function(){
that.debug($(this).attr("class")));
});
}
精彩评论