Javascript 未捕获类型错误:this.function不是函数
嗨,这是我的(短)示例代码:Javascript 未捕获类型错误:this.function不是函数,javascript,typescript,Javascript,Typescript,嗨,这是我的(短)示例代码: export class SolarSystemInfo { constructor() { this.test(); } // click on solar system clickSolarSystem() { $("body").on("click",".hex", function() { this.test(); }); } pu
export class SolarSystemInfo {
constructor() {
this.test();
}
// click on solar system
clickSolarSystem() {
$("body").on("click",".hex", function() {
this.test();
});
}
public test () {
alert('test');
}
}
我的问题是,在构造函数中,test函数被正确调用,但在调用此函数后,单击SolarSystem函数。test()我得到:未捕获类型错误:this.test不是函数
如何在函数内部类中调用test函数?感谢执行回调函数时,此
的上下文将丢失。
要解决此问题,您可以使用:
或者,您可以使用:
执行回调函数时,此
的上下文将丢失。
要解决此问题,您可以使用:
或者,您可以使用:
在没有的情况下使用test()这个不起作用?另请参见@Zooly:那肯定不起作用。这个.test超出了jquery的范围//单击SolarSystem ClicksSolarSystem(){var self=this;$($)(“body”)。在(“click”、“.hex”,function(){self.test();});}上使用test()如果没有,这个就不起作用了?另请参见@Zooly:That肯定不起作用。this.test超出了jquery的范围//单击SolarSystem clickSolarSystem(){var self=this;$(“body”)。on(“click”、“.hex”,function(){self.test();}这可能有助于解释此
在每个上下文中所指的内容。@cdbajorin更新了答案感谢帮助:这可能有助于解释此
在每个上下文中所指的内容。@cdbajorin更新了答案感谢帮助:
clickSolarSystem() {
$("body").on("click",".hex", () => {
this.test();
});
}
clickSolarSystem() {
$("body").on("click",".hex", function() {
this.test();
}).bind(this);
}