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?