[英]How to access an instance variable within a Promise callback?
假设我有一个基本的哑巴javascript类:
var FunctionX = function(configs) {
this.funcConfigs = configs;
}
FunctionX.prototype.getData = function() {
return $.get('/url');
}
FunctionX.prototype.show = function(promise) {
console.log(this.funcConfigs); // <-- this here is the promise itself, I'm looking to get the instance's configs
}
FunctionX.prototype.setup = function() {
this.GetData().then(show);
}
var f = new FunctionX({ "a": "b" });
f.setup();
现在我在show函数中尝试访问实例变量“funcConfig”。 “这”是承诺,“funcConfigs”直接返回undefined。
我尝试使用.resolveWith(this)
解决此问题,但它无法解决此问题。
如何在此范围上下文中访问实例变量?
与user2864740
达成user2864740
,问题很可能是因为当调用show
作为回调时, this
不是您所期望的。 为了使其正常工作,您需要在闭包中捕获正确的this
(例如var that = this;
),并显式调用它。
换一种说法...
FunctionX.prototype.setup = function() {
var that = this;
this.getData().then(function () {
that.show();
});
}
编辑:为了更清晰的语法(使用underscore.js):
FunctionX.prototype.setup = function() {
var that = this;
this.getData().then(_.bind(this.show, this));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.