Hi this is my (shortcuted) example code:
export class SolarSystemInfo {
constructor() {
this.test();
}
// click on solar system
clickSolarSystem() {
$("body").on("click",".hex", function() {
this.test();
});
}
public test () {
alert('test');
}
}
My problem is, that in constructor is test function called right, but in clickSolarSystem function after calling this.test() I get: Uncaught TypeError: this.test is not a function
How I have to call test function in my function inner class?
Thanks
The context of this is lost when the callback function is being executed.
To solve that you can use an arrow function:
clickSolarSystem() {
$("body").on("click",".hex", () => {
this.test();
});
}
Or you can use the bind method:
clickSolarSystem() {
$("body").on("click",".hex", function() {
this.test();
}).bind(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With