You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4:如何在回调函数中更新类属性?解决this指向问题

解决回调中this.index和this.result未定义的问题

嘿,这个问题的核心是嵌套回调函数里的this指向丢失了——你内层回调里的this已经不再指向你的类实例,自然会出现undefined的情况。下面给你几种实用的解决办法,都能实现你想要的更新类实例属性的效果:

方法1:用箭头函数继承外层this

箭头函数不会创建自己的this上下文,它会直接继承外层作用域的this,这是最简洁的解法:

submitQuiz(addsMemberPoints, pointsCallback) {
  this.getValues(this.answers, this.totalPoints, this.index, (answers, totalPoints, ranks, index) => {
    pointsCallback(answers, ranks, addsMemberPoints, totalPoints, index, (index, points) => {
      function getMember(obj) {
        return Object.keys(obj).reduce(function(a, b){
          return obj[a] > obj[b] ? a : b;
        });
      }
      // 这里的this现在指向类实例
      this.result = getMember(points);
      this.index = index;
    });
  });
}

方法2:提前保存this到变量

在回调函数外层把类实例的this存成一个变量(比如self),内层直接用这个变量访问实例属性:

submitQuiz(addsMemberPoints, pointsCallback) {
  const self = this; // 保存类实例的引用
  this.getValues(this.answers, this.totalPoints, this.index, function(answers, totalPoints, ranks, index){
    pointsCallback(answers, ranks, addsMemberPoints, totalPoints, index, function(index, points){
      function getMember(obj) {
        return Object.keys(obj).reduce(function(a, b){
          return obj[a] > obj[b] ? a : b;
        });
      }
      // 用self代替this,直接操作类实例
      self.result = getMember(points);
      self.index = index;
    });
  });
}

方法3:用bind()手动绑定this

给每个回调函数手动绑定this,强制它们的上下文指向类实例:

submitQuiz(addsMemberPoints, pointsCallback) {
  this.getValues(this.answers, this.totalPoints, this.index, function(answers, totalPoints, ranks, index){
    pointsCallback(answers, ranks, addsMemberPoints, totalPoints, index, function(index, points){
      function getMember(obj) {
        return Object.keys(obj).reduce(function(a, b){
          return obj[a] > obj[b] ? a : b;
        });
      }
      this.result = getMember(points);
      this.index = index;
    }.bind(this)); // 绑定当前回调的this为外层的this
  }.bind(this)); // 绑定getValues回调的this为类实例
}

额外建议:用async/await简化回调嵌套(可选)

如果你的getValues和pointsCallback可以改成返回Promise的形式,用async/await写法会更清晰,彻底避免回调地狱和this指向问题:

async submitQuiz(addsMemberPoints, pointsCallback) {
  // 假设getValues返回Promise,用await获取结果
  const [answers, totalPoints, ranks, index] = await this.getValues(this.answers, this.totalPoints, this.index);
  // 假设pointsCallback也返回Promise
  const [newIndex, points] = await pointsCallback(answers, ranks, addsMemberPoints, totalPoints, index);
  
  function getMember(obj) {
    return Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
  }
  
  this.result = getMember(points);
  this.index = newIndex;
}

内容的提问来源于stack exchange,提问作者Haroun Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:30:11