This comes from two different factors of how the engine will determine the this
value for the function, the thisArg
optional parameter to forEach
, and whether or not the code is in strict mode.
From MDN:
If a thisArg
parameter is provided to forEach()
, it will be passed to callback
when invoked, for use as its this
value. Otherwise, the value undefined
will be passed for use as its this
value. The this
value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
These rules are elsewhere documented as follows:
Inside a function, the value of this depends on how the function is called.
function f1(){
return this;
}
f1() === window; // global object
In this case, the value of this
is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object. (emphasis added)
Note that this behavior changes in strict mode. If you add "use strict"
to the top of the call back, it will log undefined
to the console.
In short, if you want the this
value to refer to the array, arr
, you just need to call forEach
like this:
var arr= [1,2,34,5,6,7,7,8];
arr.forEach(function(e){
console.log(this);
}, arr);