未捕获的TypeError:this.function不是函数

时间:2017-06-19 14:14:02

标签: javascript typescript

嗨,这是我的(简称)示例代码:

export class SolarSystemInfo {

    constructor() {
        this.test();
    }

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

    public test () {
        alert('test');
    }

}

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

1 个答案:

答案 0 :(得分:5)

执行回调函数时,this的上下文将丢失 要解决此问题,您可以使用arrow function

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

或者您可以使用bind method

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