Events of jQuery Vs. arrow functions?

1

When you run the following code:

$("button").on("click", function(){
   console.log("Meu valor é: " + $(this).val());   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonvalue="1">Clique-me</button>

The value of the button is returned normally. But in:

$("button").on("click", ()=>{
   console.log("Meu valor é " +$(this).val());   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonvalue="1">Clique-me</button>

Using arrow function in the event acknowledges the error in jQuery:

  

Uncaught TypeError: Can not read property 'toLowerCase' of undefined

Notice that I'm using the latest version% of jQuery%.

Someone would know why the arrow function does not work in jQuery event cases since ES6 is not something so new (also called ECMAScript 2015) released at June of 2015 (almost 3 years!)?

    
asked by anonymous 27.03.2018 / 03:01

1 answer

3

The arrow function works with jQuery, what does not work is $(this) . This is not implemented by jQuery because is not possible .

  

Arrow functions do not have their own this binding so it's technically   impossible to use the this binding jQuery provides with an arrow   function.

Free translation:

  

Arrow functions are not properly bound to this , so it is technically impossible to use the this binding provided by   jQuery in an arrow function.

This is described in the ECMAScript2015 specification :

  

An ArrowFunction does not define local bindings for arguments ,    super , this , or new.target . Any reference to arguments , super , this , or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing   environment. Typically this will be the Function Environment of an   immediately enclosing function.

Free translation:

  

An Arrow function does not define a local link for arguments ,    super , this , or new.target . Any reference to arguments , super , this or new.target in an Arrow   function must be linked to the lexical scope to which it belongs.   Typically, the scope adopted will be that of the function immediately above.

To get around the problem, you can get the event source object through the function parameter, so you can access its attributes:

$("button").on("click", event =>{
    console.log("Meu valor é " +event.target.getAttribute('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonvalue="1">Clique-me</button>
    
27.03.2018 / 04:31