我有一个问题,我觉得与 javascript 的特性有关。基本上,我试图在 Promise 的 then 函数中设置成员/类变量。例如:
this.intuitAuth.authenticate()
.then(function(oauthObj){
this.setOauthObj(oauthObj);
return oauthObj;
});
其中 this.setOauthObj(oauthObj);
设置外部对象的成员变量。现在我想也许我的问题是 this
是问题,因为我认为 this
指的是 then
函数中的函数。所以我的问题是,如何在 Promise 的 then
函数中设置成员变量?或者说有可能吗?
我想要完成此任务的原因是因为我希望从对象的实例中设置此变量,因此我不必将其作为参数传递给每个方法调用。
最佳答案
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
至少有两种方法可以解决该问题:
Bind
假设 this.intuitAuth
中使用的 this 是所需的 this,那么您可以将函数作用域绑定(bind)到该作用域,如下所示:
this.intuitAuth.authenticate()
.then(function(oauthObj){
this.setOauthObj(oauthObj);
return oauthObj;
}.bind(this));
保留对所需this
的引用。
var _this = this;
this.intuitAuth.authenticate()
.then(function(oauthObj){
_this.setOauthObj(oauthObj);
return oauthObj;
});
现在,其中任何一个都可能解决您当前的问题。但您需要了解问题存在的原因,因此您应该阅读更多有关 how the value of this
is set in a scope 的内容。 .
关于javascript - 从返回的 promise 中设置成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024483/