【发布时间】:2016-04-28 02:42:20
【问题描述】:
我有一个 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 关闭了吗?
【问题讨论】:
-
当您使用 bind() 时,它会创建另一个函数,其范围与您将通过参数传递的范围完全相同。虽然它只回答了您的最后一个问题,但请查看 Mozila 的文档:developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/…
-
@Paulpro 不太确定这应该被标记为
setTimeoutissue 的副本;因为问题以两种完全不同的方式出现。希望在 Promise 的上下文中解决他们的this范围问题的人们会立即被指向一个更间接的问题,其中接受的答案使用 2009 年的反模式。2 + 2 = 4!==((8+2)*6)/15 = 4 -
IMO 绝对不应该被标记为重复,尤其是关于超时的问题。这个问题专门关于 Promises 和答案是上帝派来的。谢谢。
标签: javascript node.js promise this q