Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this keyword inside addEventListener callback

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?

like image 409
pldg Avatar asked Aug 25 '18 11:08

pldg


1 Answers

If we are using functions which have been defined using function keyword as an event handler, then that event handler function executes in the context of the element on which event was binded

button.addEventListener('click', foo);

so, in this case, this value inside foo will be button element.

If we use arrow functions instead of them then this value will be the window object

The reason is this in an arrow function has the same value as the context in which the arrow function was created

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

More about lexical this What is lexical 'this'?

like image 103
Mohana Naga Venkat Sayempu Avatar answered Oct 26 '22 15:10

Mohana Naga Venkat Sayempu