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

 鱼鱼de眼泪2012 发布于 2023-02-13 09:22

假设我有一个基本的哑巴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.

我尝试用a来解决这个问题,.resolveWith(this)但它没有解决这个问题.

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

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

    2023-02-13 09:29 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有