【问题标题】:Javascript class this.x is not a function when calling function from inside class [duplicate]从类内部调用函数时,Javascript类this.x不是函数[重复]
【发布时间】:2023-04-03 07:26:01
【问题描述】:

我有一个按钮,当按下它时,它应该调用一个调用另一个函数的函数。这是在一个类中。

class cat{
    constructor(){
        this.event_listener();
    }

    log_2(){
        console.log("cat 2");
    }
    log_1(){
        console.log("cat 1");
        this.log_2();
    }

    event_listener(){
        document.getElementById("cat_button").addEventListener("click", this.log_1);
    }
}

let cat1 = new cat();

第一个函数this.log_1()在按下按钮时调用,并按预期输出“cat 1”,但随后报错

this.log_2 is not a function

出现在控制台上,尽管 log_2() 是在类中定义的。如何构造它以便将 log_2() 识别为函数?

【问题讨论】:

  • 您还没有将log2() 设为类的属性(类方法)。你刚刚使它成为一个独立的函数。
  • 试试.addEventListener("click", this.log_1.bind(this)).addEventListener("click", event => this.log_1())
  • 你需要绑定
  • 现代浏览器支持这种方法语法,无需绑定:jsfiddle.net/n2dtysuc

标签: javascript class oop


【解决方案1】:

this 就是所谓的函数。在这种情况下,一个事件调用了函数,所以this 引用了该事件。

您要做的是在使用 is 作为参考之前绑定方法。现在this 将引用该类的实例。

event_listener(){
  this.log_1 = this.log_1.bind(this)

  document.getElementById("cat_button").addEventListener("click", this.log_1);
}

【讨论】:

  • 这是重复的。请在发布答案之前检查是否有欺骗行为。
  • "this 是所谓的函数。在这种情况下,一个事件称为函数,所以this 指的是事件。" 这是不正确的。 this 实际上是处理程序绑定到的元素。
猜你喜欢
  • 2011-02-18
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多