I was wondering what the 'this' value (or invocation context) is of the forEach callback function. This code doesn't seem to work:
var jow = [5, 10, 45, 67];
jow.forEach(function(v, i, a){
this[i] = v + 1;
});
alert(jow);
Thx for explaining it to me.
If you dont pass second parameter to
forEach
,this
will point to the global object. To achieve what you were trying to doOutput
MDN states:
So in short, if you only provide the callback and you're in non-strict mode (the case you presented), it will be the global object (window).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
I finished construction of the forEach method and wanted to share this diagram with everyone, hope it helps someone else trying to understand its inner workings.
Inside forEach,
this
refers to the globalwindow
object. This is the case even if you call it from a different object (i.e. one you've created)