对象的变量在事件处理程序中未定义
variable of object is undefined in event handler
代码片段说明了一切。
我有一个 class 并在其构造函数中声明其变量。该变量在构造函数中工作正常,当我创建 class 的新实例时,但该变量在 eventHandler.
中显示为 undefiend
"use strict";
class InputEngine{
__mouseDown(event){
alert(this.mouse); //doesn't work here
};
constructor(){
this.mouse =3;
window.addEventListener( 'mousedown', this.__mouseDown );
}
}
let a = new InputEngine();
alert(a.mouse); //works here
<!DOCTYPE html>
<html>
<body>
<p>Click your mouse.</p>
</body>
</html>
关键字 this
根据 JavaScript 运行时正在执行的当前 "operational context" 更改它所指的内容。这意味着当事件发生时,事件处理程序在该事件的上下文中运行 - 因此 this
指的是事件对象,而不是恰好包含事件处理程序的对象。
你有几个选择。最直接的方法是使用 bind
将该函数的上下文更改为包含它的对象,因为您的代码不对事件执行任何操作。
"use strict";
class InputEngine {
__mouseDown(event) {
console.log(event.type); // event is still available
alert(this.mouse); //works
};
constructor() {
this.mouse = 3;
window.addEventListener('mousedown', this.__mouseDown.bind(this));
}
}
let a = new InputEngine();
alert(a.mouse); //works here
<!DOCTYPE html>
<html>
<body>
<p>Click your mouse.</p>
</body>
</html>
代码片段说明了一切。 我有一个 class 并在其构造函数中声明其变量。该变量在构造函数中工作正常,当我创建 class 的新实例时,但该变量在 eventHandler.
中显示为 undefiend"use strict";
class InputEngine{
__mouseDown(event){
alert(this.mouse); //doesn't work here
};
constructor(){
this.mouse =3;
window.addEventListener( 'mousedown', this.__mouseDown );
}
}
let a = new InputEngine();
alert(a.mouse); //works here
<!DOCTYPE html>
<html>
<body>
<p>Click your mouse.</p>
</body>
</html>
关键字 this
根据 JavaScript 运行时正在执行的当前 "operational context" 更改它所指的内容。这意味着当事件发生时,事件处理程序在该事件的上下文中运行 - 因此 this
指的是事件对象,而不是恰好包含事件处理程序的对象。
你有几个选择。最直接的方法是使用 bind
将该函数的上下文更改为包含它的对象,因为您的代码不对事件执行任何操作。
"use strict";
class InputEngine {
__mouseDown(event) {
console.log(event.type); // event is still available
alert(this.mouse); //works
};
constructor() {
this.mouse = 3;
window.addEventListener('mousedown', this.__mouseDown.bind(this));
}
}
let a = new InputEngine();
alert(a.mouse); //works here
<!DOCTYPE html>
<html>
<body>
<p>Click your mouse.</p>
</body>
</html>