Javascript Object - using jQuery and this



当在对象函数中使用jQuery方法(即-.each())时,"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
}
您还可以

使用 .bind 函数来更改函数的上下文。无论您向.bind提供什么参数,在函数执行时都将成为函数的所有者,因此,this的值。

test.prototype.init = function(node) {
    node.children().each(function(i,el) {
        // this = test.prototype
        // i = index of the current child of `node`
        // el = HTML node of current child
        // $(el) = jQuery object representing current child
    }.bind(this));
};

您可以在迭代之前定义要引用的对象。您将能够接近它,因为它仍在范围内。

var currentObject = this;
test.prototype.init = function(node) {
    node.children().each(function() {
        currentObject.anotherFunction();
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}

最新更新