2

In the callback function of Javascript event, this is clicked element:

  document.querySelector('#my-element').addEventListener('click', function() {
    console.log(this);  // <div id="my-element">
  });

But, when I use ES6 arrow function, this becomes undefined:

  document.querySelector('#my-element').addEventListener('click', () => {
    console.log(this);  // undefined
  });

Can someone, please, explain me this behaviour?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
  • 2
    Arrow functions have a lexical `this` binding. There are many other [questions](https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6?rq=1) around this. – James Allardice Oct 20 '16 at 15:50
  • Also a duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Oct 20 '16 at 23:46

1 Answers1

0

Arrow functions, when called, don't cause this to be bound. It'll have whatever value it had in the enclosing lexical scope. In your case, that means this in the enclosing scope is undefined.

Pointy
  • 405,095
  • 59
  • 585
  • 614