我正在向对象方法内的按钮添加事件监听器。我正在尝试添加对另一个方法函数的调用,但是当我使用 this.reset()
时,“this”指向监听器//按钮而不是对象本身。
此代码已被重构为一个对象并且之前运行良好。在这种情况下,我不需要使用“this”。
const colorGame = {
reset: function() {...},
init: function() {
for (let i = 0; i < modeSwitches.length; i++) {
modeSwitches[i].addEventListener("click", function() {
modeSwitches[0].classList.remove('selected');
modeSwitches[1].classList.remove('selected');
// These two lines are why I can't use anonymous functions
this.classList.add('selected');
this.textContent === 'Easy' ? numSquares = 3 : numSquares = 6;
this.reset();
});
}
...
resetButton.addEventListener('click', function() {
this.reset(); // This call also fails with the same error
});
Chrome 浏览器控制台错误:colorGame.js:78 Uncaught TypeError: this.reset is not a function
我的意图是使用 colorGame.reset()
并在单击按钮时调用它。
最佳答案
通过给 handleEvent
方法让您的 colorGame
对象实现 EventListener 接口(interface)。然后您可以将对象本身绑定(bind)为事件处理程序,并且当事件发生时将调用其handleEvent
方法。
handleEvent
中 this
的值将是 colorGame
对象。
const colorGame = {
handleEvent: function(event) {
// handle events here
switch (event.type) {
case "click":
this.reset();
break;
default:
console.log("unhandled event type");
}
},
reset: function() {
console.log("reset was called");
},
// Bind the colorGame object instead of binding functions
init: function() {
for (let i = 0; i < modeSwitches.length; i++) {
modeSwitches[i].addEventListener("click", colorGame);
}
resetButton.addEventListener('click', colorGame);
}
}
关于javascript - 如何从 addEventListener() 调用中调用对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997653/