0

Is it possible to set this.variable in then? I know I can pass a regular variable, but can this be done with one set in the constructor as well?

class Test {
    constructor() {
        this.variable = false;
    }

    aFunction() {
        someExternalThing(document.body, {
            option: 1
        }).then(function () {
            this.variable = true;
        });
    }
}
eskimo
  • 2,421
  • 5
  • 45
  • 81

2 Answers2

1

Yes it is possible, what you will need to change in your code is the declaration of the .then () parameter function

You must use arrow function for this to keep the class reference

Ex:

.then(() => { ... }
Henrique Viana
  • 645
  • 4
  • 12
0

The this keyword is referring to the function. Try this:

aFunction() {
  const that = this;
  someExternalThing(document.body, {
     option: 1
  }).then(function () {
     that.variable = true;
  });
}
Azure
  • 127
  • 11