Javascript对象 - 使用jQuery和this

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)

救命?

jfr*_*d00 7

将副本保存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)

  • `window.self`指的是`window`上下文.因此,用当前上下文来影响它是有意义的. (2认同)