javascript - 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。
我怎样才能回忆起这个功能?
解决方案
使用 ES6 的胖箭头函数来传递上下文,不要像 ES5 那样创建新的function()
. 你也需要使用this.stop()
,而不仅仅是stop()
this._el.onclick = () => {
console.log("[PreDS] click _el")
this.stop("click")
}
推荐阅读
- docker - 通过 dockerized Nginx 反向代理对 dockerized jenkins 的 SSL 通行证将不起作用
- javascript - 如何将组件作为道具传递给 React 中的另一个组件?
- rest - 如何使用 Axios 在 nuxtServerInit 中处理多个调度
- c++ - (VSC) 运行命令时的终端问题 (C++)
- rust - How to take the first element of a BTreeSet without clone
- linux - 如何在 lvvmpipe 软件渲染器中激活 OpenGL 3.3 核心配置文件?
- node.js - 我已经在我的 digitalocean droplet 上创建了一个 postfix 服务器,现在如何通过 nodemailer 连接?
- regex - Vim Regex 匹配所有不在括号内的逗号
- tensorflow2.0 - 如何在 tensorflow 2.0 中使用恢复的模型
- python - 在python中的文本文件的句子中重复