如何在Promise回调中访问实例变量?

时间:2013-12-03 22:14:33

标签: javascript this jquery-deferred

假设我有一个基本的哑巴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)来解决此问题,但它无法解决此问题。

如何在此范围上下文中访问实例变量?

1 个答案:

答案 0 :(得分:7)

user2864740达成一致后,问题很可能是因为this不是您在调用show作为回调时的预期。要使其正常工作,您需要在闭包中捕获正确的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));
}