当在对象函数(即 .each())中使用 jQuery 方法时,“this”变量将引用被迭代的对象。如何在没有“this”的情况下访问对象的功能?我意识到这有点令人困惑,所以:
test.prototype.init = function(node) {
node.children().each(function() {
//call test.anotherFunction() here
//Would normally call this.anotherFunction(),
// but "this" refers to the current child.
});
}
test.prototype.anotherFunction = function() {
//whatever
}
帮忙吗?
最佳答案
将 this
的副本保存到局部变量中(在本例中名为 self
,但您可以随意命名)并在嵌入式中使用保存的副本功能:
test.prototype.init = function(node) {
var self = this;
node.children().each(function() {
// use self here to reference the host object
});
}
test.prototype.anotherFunction = function() {
//whatever
}
关于Javascript 对象 - 使用 jQuery 和 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11994900/