Waterplant Waterplant - 4 years ago 213
Javascript Question

ECMAScript 6 Class this context

i am unsure about acessing the right context using classes in ECMAScript 6.

In this example I want to call the method addItem(..) of the Class {this.addItem(data.points);}
How do I bind the this-Conext of the class correctly?

Thank you very much :)

class TEST {

constructor() {}

testMethod() {

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

Answer Source

It should be something like this:

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

An alternative would be to use an arrow function, since they inherit the lexical scope of the outer 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
      });
    }
  }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download