gpt4 book ai didi

javascript - 调用JS类中的方法返回 "...is not a function"

转载 作者:行者123 更新时间:2023-12-03 02:15:21 25 4
gpt4 key购买 nike

我有一个 JS 类,它有这样的方法:

  setupComponent() {
document.getElementById("message-input").addEventListener("keydown", this._onKeyPress);
document.getElementById("send-button").addEventListener("click", this._onSend);
}

在它的正下方,有两个方法:

  _onKeyPress(event) {
if (event.code === "Enter") {
this._onSend();
}
}

_onSend() {
console.log("send");
}

我的问题是:为什么从“click”事件监听器直接调用有效(它记录消息),并且 this._onSend()方法,在 _onKeyPress 中调用返回this._onSend is not a function

还使用 this._onSend()里面setupComponent()有效。

这是与事件监听器相关的某种魔法吗?

最佳答案

当函数用作事件处理程序时,其 this 设置为从 this - JavaScript | MDN 触发事件的元素。所以你不能指望你的方法在那里,但你可以使用 Function.prototype.bind() 将你的 this 绑定(bind)到你的函数。

document.getElementById("message-input")
.addEventListener("keydown", this._onKeyPress.bind(this));

关于javascript - 调用JS类中的方法返回 "...is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49392072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com