【发布时间】:2019-05-06 00:54:04
【问题描述】:
我正在向对象方法内的按钮添加事件侦听器。我正在尝试添加对另一个方法函数的调用,但是当我使用 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() 并在单击按钮时调用它。
【问题讨论】:
标签: javascript object methods this addeventlistener