Why can't Javascript class methods access the class variables and other methods via this? I'm using Lightning Web Components, which is a similar web frontend to React. I have a component which is a class, and a property ready holding state. However, when I launch the method method, the property ready of the class is undefined. Accessing the same property from an anonymous arrow function works perfectly well.
import { LightningElement } from 'lwc';
export default class Testi extends LightningElement {
ready = false;
method() {
console.log(this.ready);
this.ready = false;
console.log(this.ready);
}
connectedCallback() {
setTimeout(() => {
console.log(this.ready);
this.ready = true;
console.log(this.ready);
}, 2000);
setTimeout(this.method, 4000);
}
}
I get the same error if I try to access other class methods from method(), they're undefined.
Instead, to access the methods and properties of the class, I need to pass this to the functions as a parameter but I'm pretty sure that's not correct:
import { LightningElement } from 'lwc';
export default class Testi extends LightningElement {
ready = false;
method(obj) {
console.log(obj.ready);
obj.ready = false;
console.log(obj.ready);
}
connectedCallback() {
setTimeout(this.method, 4000, this);
}
}