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

How to access an instance variable within a Promise callback?

本文关键字:访问 实例 变量 回调 Promise      更新时间:2024-03-14

假设我有一个基本的哑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)解决这个问题,但它不能解决这个问题。

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

user2864740一致,该问题很可能是由于show作为回调调用时this不是您所期望的那样。为了使其正常工作,您需要在闭包(例如var that = this;)中捕获适当的this,并显式调用它。

换句话说。。。

FunctionX.prototype.setup = function() {
   var that = this;
   this.getData().then(function () {
      that.show();
   });
}

编辑:为了获得更简洁的语法(使用下划线.js):

FunctionX.prototype.setup = function() {
   var that = this;
   this.getData().then(_.bind(this.show, this));
}