gpt4 book ai didi

javascript - Uncaught TypeError : this. 函数不是函数

转载 作者:行者123 更新时间:2023-12-04 16:08:09 29 4
gpt4 key购买 nike

您好,这是我的(快捷方式)示例代码:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com