javascript - 如何从 addEventListener() 调用中调用对象方法?

标签 javascript object methods this addeventlistener

我正在向对象方法内的按钮添加事件监听器。我正在尝试添加对另一个方法函数的调用,但是当我使用 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 方法。

handleEventthis 的值将是 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/

相关文章:

javascript - 如何将 Google Endpoints 与 Sencha Touch 结合使用?

javascript - 如何在Vue中捕获 Canvas 上的关键事件

javascript 使用带循环的 settimeout()

javascript - Visual Studio 和 Chrome 的 let 和 const 问题

java - 如何重新实现 System.out.print()

java - 如何调用以方法作为参数的方法?

javascript - jQuery 风格函数默认使用对象

object - 使用泛型时出现意外的 "Spread types may only be created from object types"错误

Typescript:如何用全名填充对象属性

python - 为什么方法没有引用相等性?