PA. PA. - 6 months ago 9
jQuery Question

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

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
?

Answer

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).