我有一个想要在事件发生时运行函数的类.每当函数调用时,该类实例的函数就不会运行.
class Player {
constructor() {
window.addEventListener('keypress',this.key_press);
this.keys_pressed = 0;
}
key_press(key_press) {
if(key_press.key == "w") {
console.log(key_press);
this.keys_pressed += 1;
}
console.log(this.keys_pressed);
}
}
每当调用this.key_press时,它将注销NaN.似乎该类的方法没有在运行,而是在运行copy(?).我也尝试过在key_press()中运行另一个实例函数,但它表示该函数未定义.
任何帮助表示赞赏.
最佳答案
将事件侦听器添加到窗口或DOM的任何元素时,此值指向该元素而不是Player实例.
因此,由于窗口不具有keys_pressed属性,而您将得到NaN,并且keys_pressed = 1被视为keys_pressed = undefined 1,即NaN.
为了解决这个问题,我们需要显式绑定到Player实例:
const input = document.querySelector("#input");
class Player {
constructor() {
input.addEventListener('keypress',this.key_press.bind(this));
this.keys_pressed = 0;
}
key_press(key_press) {
if(key_press.key == "w") {
this.keys_pressed += 1;
}
console.log(this.keys_pressed);
}
}
let p = new Player();
Type here: <input type="text" id="input">
我们还可以使用箭头(=>)函数从当前上下文中捕获this并将其指向Player对象的当前实例:
const input = document.querySelector("#input");
class Player {
constructor() {
input.addEventListener('keypress',(event) => this.key_press(event));
this.keys_pressed = 0;
}
key_press(key_press) {
if(key_press.key == "w") {
this.keys_pressed += 1;
}
console.log(this.keys_pressed);
}
}
let p = new Player();
Type here: <input type="text" id="input">