Why "this" refers to Window in forEach in javascript?

arrays, javascript

Solution

`.forEach()` specifies the value of `this` within the iterator based on its 2nd parameter, `thisArg`.

arr.forEach(callback[, thisArg])

So, it will only use a particular object if you provide it:

arr.forEach(function(e){
    console.log(this);
}, arr); // <---

Otherwise, the value of `this` will be the default value of a normal function call -- either `undefined` in strict mode or the global object (`window` in browsers) in non-strict.

function foo(e) {
    console.log(this);
}

foo();            // [object Window]

[1].forEach(foo); // (same)

Though, the `arr` is still provided to the iterator, just as its 3rd argument:

arr.forEach(function (e, i, arr) {
    console.log(arr);
});

Problem

If I run this code, window object gets printed to console. ``` var arr= [1,2,34,5,6,7,7,8]; arr.forEach(function(e){ console.log(this); }); ``` Why does it not refer to arr object or specific items in array object? I want to understand the reason behind it, like what's going on. `this` gets defined using by `new`, or the object invoking this function, right?

Original source

Related problems