在对象内部进行上下文切换 - 在回调中引用“this”

时间:2015-12-09 15:26:38

标签: 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使用的符号,但仍然正确减去?

2 个答案:

答案 0 :(得分:3)

bind()将确保使用正确的this引用进行调用:

.fail( _this.subtractOne.bind( _this ) );

答案 1 :(得分:3)

因为this取决于函数的调用方式,而不是如何编写

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

正因为如此,this中的this.starting--并不是您认为的。

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

.fail(_this.substractOne.bind(_this));
相关问题