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

标签 javascript typescript

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

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/

相关文章:

javascript - 如何通过命名空间从所有 DOM 元素中有效地删除事件监听器?

javascript - 词法作用域/闭包和全局函数递归

javascript - 传递数据查看时JS中的"SyntaxError: unterminated string literal"

angular - 将 ionic 应用程序转换为延迟加载

typescript - 为什么 react-native ts 需要 typescript-transformer 和自定义 rn-cli 配置?

javascript - webgl、纹理坐标和obj

javascript - 将数组转换为 Observable<T[]> 的类型

javascript - 如何在 typescript 中定义计算属性

node.js - 使用 `__dirname` 引用本地文件的 typescript

typescript - Typescript 2 中的尖括号和 "as' ' 有什么区别?