从返回的承诺中设置成员变量
Setting Member Variable from within returned promise
我有一个问题,我觉得它与 javascript 的特质有关。基本上,我试图将一个 member/class 变量设置为 from 在承诺的 then 函数中。例如:
this.intuitAuth.authenticate()
.then(function(oauthObj){
this.setOauthObj(oauthObj);
return oauthObj;
});
其中this.setOauthObj(oauthObj);
为外部对象设置成员变量。现在我想也许我的问题是 this
是问题,因为我认为 this
指的是 then
函数中的函数。所以我的问题是,如何从承诺的 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,那么您可以将函数作用域绑定到那个作为如下:
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 的特质有关。基本上,我试图将一个 member/class 变量设置为 from 在承诺的 then 函数中。例如:
this.intuitAuth.authenticate()
.then(function(oauthObj){
this.setOauthObj(oauthObj);
return oauthObj;
});
其中this.setOauthObj(oauthObj);
为外部对象设置成员变量。现在我想也许我的问题是 this
是问题,因为我认为 this
指的是 then
函数中的函数。所以我的问题是,如何从承诺的 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,那么您可以将函数作用域绑定到那个作为如下:
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.