How to Access the Correct this Inside a Callback

Here are several ways to access parent context inside child context.

  1. Use ES6 Arrow functions.

An arrow function does not have its own bindings to this or super, this is inherited from the scope. In regular function, this is the function itself (it has its own scope).

getData() {
ajaxRequest(query).then(response => {
this.data = response.data;
});
}
  1. Store reference to context/this inside another variable, If you can’t use ES6 syntax.
getData() {
let self = this;
ajaxRequest(query).then(function(response) {
self.data = response.data;
});
}

References

[1] Arrow function expressions

[2] How to access the correct this inside a callback?