-2

We know that we have to preserve the value of this in callbacks in order to execute them with appropriate context. For example:

someArr.forEach(function(el) { console.log(this); });

Here this will be referring to window or undefined when we use use strict.

But when we are adding an event for example:

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

Here this refers to the button which is clicked. How come in this callback we dont have to bind any this while in former case we have to bind it explicitly. I can be wrong so please clarify my doubt.

Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
  • `this` in your `click` callback is not the same `this` as the `this` in the context where you attach the event handler (i.e. here: `this && someBtn.addEventHandler`). It's a different `this`. It's being changed. If you bound it, `this` inside the event handler would *not* refer to the button. – deceze Aug 07 '17 at 11:06

1 Answers1

1

The value of this depends on how the function is called.

When you pass the function to addEventListener or to forEach then you are setting things up for code written by other people to call it.

That code will call the function in different ways depending on the intentions of the people who wrote it.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • But i dont get that in above cases which i have put in question....why in case of addEventListener we have the element's reference in the callback without even binding it to the callback?? –  Aug 07 '17 at 11:08
  • @JotWaraich — Because whomever designed the `addEventListener` API thought that would be useful – Quentin Aug 07 '17 at 11:09
  • @Jot Because the event handler is going to be called with `this` set to the element on which the event happened. `addEventListener` takes care of that. – deceze Aug 07 '17 at 11:09
  • So we can say that it also depends on the type of callback what it would have as `this` inside –  Aug 07 '17 at 11:12
  • No. It depends on the code that calls the callback. – Quentin Aug 07 '17 at 11:12
  • Now i get it. So there is a different code which runs the forEach callback and different code which runs the addEventListener callback this time setting the value of `this` in the way –  Aug 07 '17 at 11:15