Led*_*vin 4 javascript jquery object this javascript-objects
在对象函数(即 - .each())中使用jQuery方法时,"this"变量将引用正在迭代的对象.如何在没有"this"的情况下访问Object的功能?我意识到这有点令人困惑,所以:
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
}
Run Code Online (Sandbox Code Playgroud)
救命?
将副本保存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
}
Run Code Online (Sandbox Code Playgroud)