I read some other answer about this topic but I'm not sure I understand how this
keyword works inside addEventListener
.
const button = document.querySelector('button');
function foo() { console.log(this) }
button.addEventListener('click', foo);
foo
is a regular function inside addEventListener
, it's not a method on button
object. When foo
is called should be executed in the context of the global object, therefore this
should be equal to window
and not to button
.
Looks like a situation similar to this example:
const obj = {
method: function (cb) {
console.log('method', this); // `this` === `obj`
return cb();
}
};
obj.method(function() {
console.log('cb', this); // `this` === `window`
});
Where obj
could be considered as button
, method
could be addEventListener
and cb
the callback inside addEventListener
.
I know I can use bind
to change the context of this
but I want to understand more in depth why it works like that.
Why this
inside addEventListener
callback is invoked on the context of the current element instead of the global object?