1

I recently stumbled upon how this is defined at runtime in event listeners. As I understood so far, this is defined very dynamic at runtime. This means that the value of this points to the object a method is called upon:

object.doSomething() // this in doSomething points to object

Arrow functions on the other hand act differently. They don't have a this value, so this is taken from the execution context in which the arrow function is declared. This is why the instantly invoced arrow function logs the object even if it is not called on it:

const object = {
  name: 'foo',
  doSomething: doSomething,
};

function doSomething() {
  (function () {
    console.log(this); // Window
  })();
  (() => {
    console.log(this); // object foo
  })();
}

object.doSomething();

So far so good. Things seem to work differently in addEventListener:

someElement.addEventListener('click', function () {
  console.log(this); // someElement
});

someElement.addEventListener('mouseover', () => {
  console.log(this); // window
});

Since addEventListener is called on someElement I would expect this inside addEventListener to point to that object. The regular callback function however is called as soon as the event occurs. It is not called on the object and should therefor point the window. But actually it points on someElement.

In the second example we see, that the arrowfunction logs window. Since I expect this inside addEventListener to point to someElement, this inside the arrow function should also point to someElement.

Long story short. this inside addEventListener behaves contrary to what I expected. Why is this?

FelHa
  • 1,043
  • 11
  • 24
  • 2
    The Web API [specifies](https://dom.spec.whatwg.org/#ref-for-dom-eventtarget-addeventlistener) that the target of the callback be the element the event was raised on. When supplied with an arrow function, however, the target (ie. `this`) of the function cannot be set as the ECMAScript specification demands that it is automatically set *lexically*. Hence your observation. – Ben Aston Oct 08 '20 at 15:22
  • This is not about the `addEventListener` itself, but it is about its callback function. – SMAKSS Oct 08 '20 at 15:22
  • Actually I know what arrow functions are. So the linked questions do not answer my question. @BenAston thank you! This answers my question – FelHa Oct 08 '20 at 15:28

0 Answers0