所以我有一个包含几个方法的类,其中一个方法用作回调。但是根据我声明回调的方式,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/