您好,这是我的(快捷方式)示例代码:
export class SolarSystemInfo {
constructor() {
this.test();
}
// click on solar system
clickSolarSystem() {
$("body").on("click",".hex", function() {
this.test();
});
}
public test () {
alert('test');
}
}
我的问题是,在构造函数中调用 test 函数是正确的,但是在调用 this.test() 之后在 clickSolarSystem 函数中我得到了: Uncaught TypeError: this.test is not a function
如何在我的函数内部类中调用 test 函数?
谢谢
最佳答案
在执行回调函数时,this
的上下文会丢失。
要解决这个问题,您可以使用 arrow function :
clickSolarSystem() {
$("body").on("click",".hex", () => {
this.test();
});
}
或者您可以使用 bind method :
clickSolarSystem() {
$("body").on("click",".hex", function() {
this.test();
}).bind(this);
}
关于javascript - Uncaught TypeError : this. 函数不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632946/