我有一个 javascript 类,每个方法都返回一个 Q
promise 。我想知道为什么 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
吗?
最佳答案
this
始终是调用该方法的对象。但是,当将方法传递给 then()
时,您并没有调用它!该方法将存储在某个地方并稍后从那里调用。如果你想保留 this
,你必须这样做:
.then(() => this.method2())
或者如果你必须以 ES6 之前的方式来做,你需要在之前保留 this
:
var that = this;
// ...
.then(function() { that.method2() })
关于javascript - 为什么 'this' 在使用 Promise 时在类方法内部未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34930771/