0

i'm unsure about accessing this context in ECMAScript 6 class .

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?

class TEST {

  constructor() {}

  testMethod() {

    for (let i = 1; i <= 10; i++) {
       $.getJSON("test/" + i + ".json", function (data) {
         this.addItem(data.points);
       });
    }
  }
}
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Waterplant
  • 13
  • 5

1 Answers1

3

Try the below snippet.

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

Alternative Way:

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
      });
    }
  }
}
Venkat.R
  • 7,420
  • 5
  • 42
  • 63
toskv
  • 30,680
  • 7
  • 72
  • 74
  • Thank you very much :) What way is the more "cleaner" or "more usual" way? – Waterplant Dec 26 '15 at 16:06
  • 2
    the arrow function was made for situations when you want the same lexical scope in a callback as in the clojure it was created it, so I would pick that over the bind function. :) – toskv Dec 26 '15 at 16:08
  • 1
    `this` is not the same as "scope". Don't confuse those two. Scope is not "bound". – Felix Kling Dec 26 '15 at 16:47
  • Thanks for spotting that, it's an unfortunate turn of phrase, is inherit better? :) – toskv Dec 26 '15 at 16:53