Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  142] [ 1]  / answers: 1 / hits: 21848  / 7 Years ago, mon, june 19, 2017, 12:00:00

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


More From » typescript

 Answers
8

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);
}

[#57385] Saturday, June 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;