I have a simple click handler
<h1 id="test">
$('#test').click( ev => {
var $test = $(this);
console.log($test.text());
})
but it does not work, $(this)
is not the emitter element. If I inspect this
I see a "window" (?) (??) (??!)
also, if I change my code to
var $test = $(ev.toElement);
it works perfectly.
how can this be? what is in my code that prevents jquery to correctly pass the element in this
?
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 ownthis
,arguments
,super
, ornew.target
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With