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

后端 未结 3 1080
猫巷女王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:16

    Arrow functions do have a "lexical this". That means that the value of this inside of your function is the same as outside of it. And since the value of this in the global scope is window you also get that value in your event handler.

    You have to use a normal function like this if you want your code to work:

    $('#test').click( function(){
     var $test = $(this);
     console.log($test.text());
    })
    

    You can't set the value of this of an arrow function in any way.

    var f1 = () => this
    var f2 = function(){return this}
    f1.call("hello") // --> window
    f2.call("hello") // --> "hello"
    

    this is always lexical for arrow functions

    function foo(){
      return () => this
    }
    
    foo.call(true).call(false) // --> true
    

    For more information on arrow functions have a look at the mdn reference.

    0 讨论(0)
  • 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:

    <!-- HTML -->
    
    <button>Click me to say hello!</button>
    
    // 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
    0 讨论(0)
  • 2021-01-19 12:20

    Arrow functions do not bind this, arguments etc. MDN.

    An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).

    0 讨论(0)
提交回复
热议问题