typescript 未捕获的类型错误:this.function 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44632946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:38:57  来源:igfitidea点击:

Uncaught TypeError: this.function is not a function

javascripttypescript

提问by Thomas Hoffner

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 testfunction called right, but in clickSolarSystemfunction after calling this.test()I get: Uncaught TypeError: this.test is not a function
How I have to call testfunction in my function inner class?
Thanks

我的问题是,在构造函数中,测试函数被正确调用,但是在调用this.test()后在clickSolarSystem函数中,我得到:未捕获的类型错误:this.test 不是函数我如何在我的函数内部类中调用测试函数? 谢谢

回答by Nitzan Tomer

The context of thisis lost when the callback function is being executed.
To solve that you can use an arrow function:

this执行回调函数时的上下文丢失。
要解决这个问题,您可以使用箭头函数

clickSolarSystem() {
    $("body").on("click",".hex", () => {
        this.test();
    }); 
}

Or you can use the bind method:

或者您可以使用绑定方法

clickSolarSystem() {
    $("body").on("click",".hex", function() {
        this.test();
    }).bind(this); 
}