4

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

LiH
  • 382
  • 3
  • 7
  • 21

1 Answers1

11

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); 
}
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299