13 of 17 menu

The "this" Error in JavaScript Arrow Event Handlers

Lately, it has become fashionable to use arrow functions everywhere instead of regular ones. However, these functions have a catch - they do not preserve this. Let's look at the problem you might encounter because of this.

Let's say we have a button:

<button>text</button>

Let's get a reference to this button in a variable:

let button = document.querySelector('button');

Let's attach an event handler to the button using an arrow function:

button.addEventListener('click', () => { console.log(this.textContent); });

This is where a surprise awaits us: this in the arrow function will not refer to the element where the event occurred.

Let's see what can be done about this.

First Solution

You can stop using this and use the variable to which the event is bound:

button.addEventListener('click', () => { console.log(button.textContent); });

Second Solution

You can get the element to which the event is bound via event.target:

button.addEventListener('click', (event) => { console.log(event.target.textContent); });

Third Solution

You can abandon the arrow function and use a regular one:

button.addEventListener('click', function() { console.log(this.textContent); });
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline