javascript - ECMAScript 6 将此上下文分类

标签 javascript ecmascript-6

我不确定是否访问 this ECMAScript 6 类中的上下文。

在这个例子中我想调用方法 addItem(..)类(class){this.addItem(data.points);}

如何正确绑定(bind)类的 this-Conext?

class TEST {

  constructor() {}

  testMethod() {

    for (let i = 1; i <= 10; i++) {
       $.getJSON("test/" + i + ".json", function (data) {
         this.addItem(data.points);
       });
    }
  }
}

最佳答案

尝试下面的代码片段。

class TEST {

  constructor() {}

  testMethod() {

    for (let i = 1; i <= 10; i++) {
      $.getJSON("test/" + i + ".json", function(data) {
        this.addItem(data.points);
      }.bind(this)); // bind the this of the function you send to $.getJSON to the this of testMethod
    }
  }
}

替代方式:

使用箭头函数,因为它们继承了外部 clojure 的词法范围。

class TEST {

  constructor() {}

  testMethod() {

    for (let i = 1; i <= 10; i++) {
      $.getJSON("test/" + i + ".json", data => {
        this.addItem(data.points); // this is the this of testMethod
      });
    }
  }
}

关于javascript - ECMAScript 6 将此上下文分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472804/

相关文章:

javascript - 使用 BlueImp jQuery fileupload 将绝对 href 和 src url 附加请求 uri

javascript - ES6 导入/导出语法的困难

javascript - 如何在 TypeScript 中映射多个类型的数组?

javascript - 选择某些值并在 ES6 中按字母顺序排序

javascript - 如何在 Google Apps 脚本中使用 google.script.run 将 JS 对象传递给服务器函数?

java - 如何使用google map3在struts2中绘制折线

javascript - 如何在不挂起几分钟的情况下记录 60MB 以上的 HTML5 拖放文件的内容?

javascript - Firebase,两个项目相同的数据库?

javascript - 在 React-Native 中将指定 HTML 标签之间的文本内容设为大写

javascript - ESlint 编译 es6 导入/导出语句失败