javascript - 对象内部的上下文切换 - 在回调中引用 'this'

标签 javascript

所以我有一个包含几个方法的类,其中一个方法用作回调。但是根据我声明回调的方式,this 的指针有一个切换的上下文。我想知道如何在 this 的指针是对象本身的情况下进行这项工作。

我的问题的一个例子:

return {
    init: function(){
        this.starting = 0;
        var _this = this;
        $.ajax({/* some params */})
        .done(function(response){
            _this.addOne(); // here the context is fine, one gets added
        })
        .fail( _this.subtractOne ); // the callback points to the function below, 
                                    // but 'this' doesn't point to the same thing
    },
    addOne: function(){
        this.starting++;
    },
    subtractOne: function(){
        this.starting--;
    }
}

如何使用 .fail 使用的符号,但仍然正确减去?

最佳答案

因为this是由函数调用的方式决定的,而不是编写的方式。

jQuery 调用其回调函数时将 this 绑定(bind)到当前对 jQuery 有意义的任何内容(例如,对于事件处理程序,this 绑定(bind)到 DOM 元素触发事件)。

因此,this.starting-- 中的 this 并不是您所想的那样。

您可以通过将 .bind() 的结果传递给您的函数来强制 this 成为您想要的任何内容,如下所示:

.fail(_this.substractOne.bind(_this));

关于javascript - 对象内部的上下文切换 - 在回调中引用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34182574/

相关文章:

javascript - 创建具有输入和标签的嵌套 div,然后在输入上分配事件的最佳方法是什么?

javascript - 从 Node 模块在 VueJS 中提供 firebaseui.css 的问题

javascript - Node gyp 重建错误。为什么?

javascript - 如何找到具有属性的元素并更改 javascript 中的属性值?

javascript - 传单,否则 if = 不显示标记

javascript - 需要帮助从网站上删除 iFrame 黑客吗?

javascript - 在 .js 中设置默认选项卡

javascript - 基于 DOM 的跨站点脚本

javascript - 循环遍历数组内部时如何获取数组的名称?

javascript - 如何将数据库内容显示到EJS网页?