Javascript 对象 - 使用 jQuery 和 this

标签 javascript jquery object this javascript-objects

当在对象函数(即 .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/

相关文章:

javascript - 如何使用大量粒子获得更好的性能? Canvas

angular - 根据每个对象中的字段过滤对象数组

javascript - 对象解构赋值在构造函数中表现异常

Java是按值传递吗?

javascript - 清除调整大小刷新时的 Jquery css 更改

javascript - 如何绑定(bind)每次 ng-click 提交一次?

javascript - 在 JavaScript 中添加两个引号

javascript - jQuery ajax 发送前

javascript - 如果光标已经在元素上,则在页面加载时触发鼠标进入事件

javascript - 使用 Object.assign 替换状态