JQuery vs. arrow functions events?

When executing 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>
<button value="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>
<button value="1">Clique-me</button>

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

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

See I'm using the latest 3.3.1 version of jQuery.

Would anyone know why the arrow function it doesn't work in jQuery event cases since ES6 isn'T something as new as this (also called ECMAScript 2015) released in June 2015 (almost 3 years!)?

Author: Sam, 2018-03-27

1 answers

The arrow function works with jQuery, what doesn't work is $(this). This is not implementing by jQuery because is not possible .

Arrow functions don't 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 binding to this provided by jQuery in a 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:

A 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 a Arrow function must be linked to lexical scope to which it belongs. Typically, the scope adopted will be that of the function immediately above.

To work 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>
<button value="1">Clique-me</button>
 3
Author: Felipe Marinho, 2018-03-27 14:59:33