0

Why does this point inside array.forEach as window object. I understand this is because its a callback function .If so in case of event handlers also where we pass the handler function as a callback function we should be getting this to be the window, but we get the object (i.e. an HTML element) .How are both different?

In below example I have an array method which takes a callback.

var videoPlayer = {
    title: 'Main player',
    tags: ['a', 'b', 'c'],
    getTags() {
        this.tags.forEach(function(item) {
            console.log(this) //window object  
        })
    }
}
videoPlayer.getTags()

PS: I understand the fix and passing the this as a second parameter in the forEach. But I am interested to know the working of this keyword

VLAZ
  • 22,934
  • 9
  • 44
  • 60
  • 1
    That is how `forEach` works. It calls your callback function without any specific `this` (so the global object or undefined). If you want to use the `this` that you have in the surrounding function, then use an arrow function, or pass the `thisArg` to `forEach`. – trincot Mar 26 '22 at 09:36

0 Answers0