我有一个 javascript 类,每个方法都返回一个 Q
承诺。我想知道为什么 this
在 method2
和 method3
中未定义。有没有更正确的方法来编写这段代码?
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2)
.then(this.method3);
}
MyClass.prototype.method1 = function(){
// ...q stuff...
console.log(this.options); // logs "opts" object
return deferred.promise;
};
MyClass.prototype.method2 = function(method1resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
MyClass.prototype.method3 = function(method2resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
我可以使用 bind
解决这个问题:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
但不完全确定为什么 bind
是必要的;是 .then()
杀死 this
关闭?
原文由 SteamDev 发布,翻译遵循 CC BY-SA 4.0 许可协议
this
始终是调用该方法的对象。但是,当将方法传递给then()
时,您没有调用它!该方法将存储在某个地方并稍后从那里调用。如果你想保留this
,你必须这样做:或者,如果您必须以 ES6 之前的方式执行此操作,则需要在之前保留
this
: