如何在addEventListener()调用中调用对象方法?

时间:2019-05-06 00:54:05

标签: 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()并在单击按钮时调用它。

3 个答案:

答案 0 :(得分:2)

更改事件监听器以使用匿名函数,例如: static int recursionTest(Integer counter) { // assume 1 is passed in Boolean ok = false; return recursionTestHelper(counter, ok, new HashMap<Integer, Integer>()); } // Goal is to recurse 5 times, growing counter, and after two stack frame pops, return -1, else 0 static int recursionTestHelper(int counter, Boolean baseCaseHit, HashMap<Integer, Integer> memo) { if (counter == 5) { // Let this recurse 5 time **baseCaseHit** = true; // This Boolean only changes in frame #5 memo.put(0, 3); // Store 3 at key 0, for stack frame 3 to catch later. } else { int result = recursionTestHelper(counter + 1, baseCaseHit, memo); } int stackFrameToImpact = memo.get(0); if (counter == stackFrameToImpact) // *This works fine.* return -1; // This signals that all worked as hoped. return 0; // This signals that we're still just popping off stack frames. } public static void main(String[] args) { System.out.println( recursionTest(1) ); } modeSwitches[i].addEventListener("click", () => this.reset());

答案 1 :(得分:1)

只需将this存储到另一个变量中。我通常将其称为that

const colorGame = {
reset: function() {...},

init: function() {

    let that = this;
    for (let i = 0; i < modeSwitches.length; i++) {
        modeSwitches[i].addEventListener("click", function() {
            ...
            that.reset();
        });
    }
    ...
    resetButton.addEventListener('click', function() {
        that.reset(); 
    });

答案 2 :(得分:1)

让您的colorGame对象通过为其提供一个handleEvent方法来实现 EventListener接口 。然后,您可以将对象本身绑定为事件处理程序,并在事件发生时调用其handleEvent方法。

thishandleEvent的值将是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);
  }
}