how can $(this) not be the element that triggered the event in a jquery click handler?

后端 未结 3 1079
猫巷女王i
猫巷女王i 2021-01-19 11:42

I have a simple click handler

$(\'#test\').click( ev => {
   var $test = $(this);
   console.log($test         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-19 12:18

    Yury Tarabanko has already answered your question: Arrow functions do not bind this. This can come in handy if you're writing something like this:

    
    
    
    
    // JS:
    
    class Foo{
      constructor( $button ){
        this.$button = $button;
    
        $button.click(() => {
          this.sayHello();
        });
      }
    
      sayHello() {
        alert('Hi');
      }
    }
    
    new Foo( $('button') );
    

    Check out this fiddle: https://jsfiddle.net/bhkkLfty/

    Play with this code for a while. Just change () => {} into function() {} and console.log this.

    Edit: For more information, check out one of the following articles:

    • https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/
    • http://www.2ality.com/2016/02/arrow-functions-vs-bind.html

提交回复
热议问题