JavaScript: the this keyword with arrow functions and event handlers

JavaScript: the this keyword with arrow functions and event handlers

In JavaScript, arrow functions create a special condition in handling events.

In JavaScript, arrow functions create a special condition in handling events.

Let's consider the following code:


const button = document.querySelector('#btn');

button.addEventListener('click', evt => {
    console.log(this); // It does not point to button
}, false);

If we still want to use arrow functions with events, we need to reference the property target of the Event object in order to address this problem.


const button = document.querySelector('#btn');

button.addEventListener('click', evt => {
    console.log(evt.target); // It points to button
}, false);