I recently faced the classical problem of accessing class members into an anonymous function.
class A {
constructor(a) {
this.a = a;
}
printA() {
console.log(this.a);
}
useAnonymousFunction() {
setTimeout(function(){
this.printA();
})
}
}
instance = new A(42);
instance.useAnonymousFunction();//TypeError: this.printA is not a function
The solution I found was to use the classical trick of storing "this" into an other variable.
useAnonymousFunction() {
//that or self
let that = this;
setTimeout(function(){
that.printA();
})
}
I used setTimeout in my example for readability but it could have been for setting an event or for an AJAX request.
This solution seems quite ugly. I tried to look for something more elegant but cannot find anything. There were some bind-based solutions but it seems like they don't work all the time (and they are even less elegant).
Is this solution really the norm even in EC6 ? Is using elements that use anonymous functions the real ugly part ?
Thank you in advance for your insight !