使用 Promise 时,为什么在类方法中未定义“this"? [英] Why is 'this' undefined inside class method when using promises?
问题描述
我有一个 javascript 类,每个方法都返回一个 Q
承诺.我想知道为什么 this
在 method2
和 method3
中没有定义.有没有更正确的方法来编写这段代码?
I have a javascript class, and each method returns a Q
promise. I want to know why this
is undefined in method2
and method3
. Is there a more correct way to write this code?
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
解决这个问题:
I can fix this by using bind
:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
但不完全确定为什么 bind
是必要的;.then()
是否关闭了 this
?
But not entirely sure why bind
is necessary; is .then()
killing this
off?
推荐答案
this
始终是调用方法的对象.但是,当将方法传递给 then()
时,您并没有调用它!该方法将存储在某个地方并稍后从那里调用.如果你想保留this
,你必须这样做:
this
is always the object the method is called on. However, when passing the method to then()
, you are not calling it! The method will be stored somewhere and called from there later. If you want to preserve this
, you will have to do it like this:
.then(() => this.method2())
或者如果你必须按照 ES6 之前的方式来做,你需要在之前保留 this
:
or if you have to do it the pre-ES6 way, you need to preserve this
before:
var that = this;
// ...
.then(function() { that.method2() })
这篇关于使用 Promise 时,为什么在类方法中未定义“this"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!