javascript ES6 类 - 从点击事件调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49422807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:35:14  来源:igfitidea点击:

ES6 Classes - Calling methods from a click event

javascriptecmascript-6es6-class

提问by barrylachapelle

I am new to ECMA classes.

我是 ECMA 课程的新手。

In the following code, I have built a button class that is working fine. Now I am trying to call the prev_image() method from inside the click eventlistener. I know 'this' refers to the button instance but am not sure how to call a method from the Gallery class. Thanks for any help.

在以下代码中,我构建了一个运行良好的按钮类。现在我试图从单击事件侦听器内部调用 prev_image() 方法。我知道“this”指的是按钮实例,但不确定如何从 Gallery 类调用方法。谢谢你的帮助。

class Gallery{

    constructor(){
    }

    draw(){

        //build button
        prevbtn.draw();

        //button listener
        document.getElementById('prevbtn').addEventListener('click', function(){
            this.prev_image();   <--- this errors out
            console.log('pressed'); <--this works
        });

    }

    prev_image(){
        console.log('previous image!');
    }

}

回答by Saikat Hajra

document.getElementById('prevbtn').addEventListener('click', ()=>{
            this.prev_image();   
            console.log('pressed');
        });

Use the arrow function here.Arrow function does not have its own thisit uses thisfrom the code that contains the Arrow Function

在此处使用箭头函数。箭头函数没有自己的函数,thisthis从包含箭头函数的代码中使用

回答by brk

Try it by binding the context using .bind(this)

通过使用绑定上下文来尝试 .bind(this)

class Gallery {

  constructor() {}

  draw() {

    //build button
    //prevbtn.draw();

    //button listener
    document.getElementById('prevbtn').addEventListener('click', function() {
      this.prev_image();
      console.log('pressed');
    }.bind(this));

  }
  // prevbtn.draw(){
  //console.log('prev btn')
  //}

  prev_image() {
    console.log('previous image!');
  }

}

var x = new Gallery();
x.draw();
<button id='prevbtn'>Click</button>

回答by cbll

With a function that way, you need to bind this. However, change the function to an arrow function:

使用这种方式的函数,您需要绑定this. 但是,将函数更改为箭头函数:

prev_image = () => {
    console.log('previous image!');
}

And it should work. You no longer need to bind this, and it's also a lot cleaner.

它应该工作。你不再需要 bind this,它也干净了很多。