【问题标题】:"x is not a function" in js when using class [duplicate]使用类时js中的“x不是函数”[重复]
【发布时间】: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


【解决方案1】:

class Test {
constructor() {
}
butClick() {
    console.log("clicked");
    this.doThis();
}
doThis(){
    console.log("Inside doThis")
  }
}

t1 = new Test();

const button = document.getElementById("but1")
button.addEventListener('click', event => {
event.preventDefault()
// Call doThis method on t1, the instance...
t1.doThis()
})
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <button id="but1">Click me</button>
    <script src="test.js"></script>
</body>
</html>

我写了一些关于在 JS 中使用类的简短而有用的文章,应该有帮助,请转到文章here

【讨论】:

  • 这不是一个好的选择,尤其是在您有多个实例的情况下。它是一个经常发生的类。
【解决方案2】:

this.button.addEventListener("click", this.butClick); 应该是this.button.addEventListener("click", this.butClick.bind(this));

没有bind(this)butClick 中的this 只是button 元素,而不是class Test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2023-04-03
    • 2017-09-26
    • 2018-12-02
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多