【问题标题】:How to access an instance variable within a Promise callback?如何在 Promise 回调中访问实例变量?
【发布时间】:2013-12-03 22:14:33
【问题描述】:

假设我有一个基本的哑 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”。 “this”是promise,“funcConfigs”直接返回undefined。

我尝试使用.resolveWith(this) 解决此问题,但它没有解决此问题。

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

【问题讨论】:

标签: javascript this jquery-deferred


【解决方案1】:

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));
}

【讨论】:

  • 是的,但它完全违背了使用承诺的目标,即链接以使代码更清晰。
  • 嗯...我不确定我是否同意你关于违背承诺的目的。我们仍然使用 Promise 的回调特性将函数链接在一起,我们只是链接一个包装现有函数的新函数。如果只是语法更简洁的问题,请参阅我的编辑。
  • 下划线是从哪里来的?
  • @Beetroot-Beetroot 它来自 underscorejs (underscorejs.org/#bind)。这个想法很好,但我不能使用 UnderscoreJS。幸运的是,原生 js 函数 bind 足以通过this.getData().then(this.show.bind(this)); 解决问题。
  • @Beetroot-Beetroot 公平的问题,我更喜欢原始语法,不值得为此目的引入 underscore.js,但如果您已经将它用于其他用途,则很有用。
猜你喜欢
  • 2017-03-10
  • 1970-01-01
  • 2017-05-04
  • 2021-04-21
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
相关资源
最近更新 更多