首页 > 解决方案 > Javascript - 如何从内部异步函数调用内部类函数?

问题描述

我正在编写一个简单的 js 类,它查找一个 div 并向其中注入一个 img 标签。

如果用户单击 div,我需要调用内部函数stop() 。

class PreDS {

constructor() {
    console.log("[PreDS] constr")
    this._el = document.querySelector(".imgOrari")
    if (this._el){
        this._el.innerHTML = "<img id='imgOrariImg'>";
        this._el.onclick =
            function(){
                console.log("[PreDS] click _el")
-->             stop("click")
            }
    }
    else console.error("class imgOrari not found")
}


stop(){
...
}

问题是这样定义的onclick处理程序不在对象的上下文中,因此该函数是undefined

我怎样才能回忆起这个功能?

标签: javascript

解决方案


使用 ES6 的胖箭头函数来传递上下文,不要像 ES5 那样创建新的function(). 你也需要使用this.stop(),而不仅仅是stop()

this._el.onclick = () => {
                console.log("[PreDS] click _el")
                this.stop("click")
            }

推荐阅读