【发布时间】:2022-01-11 15:03:28
【问题描述】:
我是 JS 新手,尤其是 JS 类。 我不完全理解课程是如何运作的。请帮助我解决以下问题。 这是一个带有按钮的简单页面。我希望它在单击按钮后运行一个函数(doThis())。但它给出了一个错误,说明该函数未定义。
class Test {
constructor() {
this.button = document.getElementById("but1");
this.button.addEventListener("click", this.butClick);
}
butClick() {
console.log("clicked");
this.doThis();
}
doThis(){
console.log("Inside doThis")
}
}
t1 = new Test();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<button id="but1">Click me</button>
<script src="test.js"></script>
</body>
</html>
【问题讨论】:
-
在单击事件侦听器中,this 指的是按钮,而不是您的类。我无法告诉你为什么会这样,但希望能帮助你解决问题。
-
您可以绑定函数,但更简单的选择是只使用箭头函数 -> ` this.button.addEventListener("click", () => this.butClick());`
标签: javascript html typescript function class