The invocation context (this) of the forEach function call

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.

Answers:

Answer

MDN states:

array.forEach(callback[, thisArg])

If a thisArg parameter is provided to forEach, it will be used as the this value for each callback invocation as if callback.call(thisArg, element, index, array) was called. If thisArg is undefined or null, the this value within the function depends on whether the function is in strict mode or not (passed value if in strict mode, global object if in non-strict mode).

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

Answer

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.

The forEach method

Answer

Inside forEach, this refers to the global window object. This is the case even if you call it from a different object (i.e. one you've created)

window.foo = 'window';

var MyObj = function(){
  this.foo = 'object';
};

MyObj.prototype.itirate = function () {
  var _this = this;

  [''].forEach(function(val, index, arr){
    console.log('this: ' + this.foo); // logs 'window'
    console.log('_this: ' + _this.foo); // logs 'object'
  });
};

var newObj = new MyObj();

newObj.itirate();
// this: window
// _this: object
Answer

If you dont pass second parameter to forEach, this will point to the global object. To achieve what you were trying to do

var jow = [5, 10, 45, 67];

jow.forEach(function(v, i, a) {
    a[i] = v + 1;
});

console.log(jow);

Output

[ 6, 11, 46, 68 ]
Answer

I have a very simple approach for the 'this' context question and it goes like this: whenever you want to know what is the context of 'this', check who is left to the caller if there is no caller to the left than it is the global else it is that object instance:

Examples:

let obj = { name:"test", fun:printName }

function printName(){
  console.log(this.name)
}

//who is left to the caller? obj! so obj will be 'this'
obj.fun() //test

//who is left to the caller? global! so global will be 'this'
printName() //undefined (global has no name property)

So, for the 'foreach' case when you give a callback function what actually happens in foreach implementation is something like that:

--> you call [1,2,3].foreach(callback,'optional This')

 foreach(arr,cb)
 {
  for(i=0; i<arr.len;i++)
  {
   //who is left to the caller? global! so it will be 'this'
   cb(arr[i])
  }
 }

Unless - you give it the optional 'this' or you bind the callback with a this (for example arrow function) if that happens than the called callback already has a 'this' obj which kind of 'blocks' you from changing it's given context more on bind can be found here enter link description here But basically the bind implementation look as follows:

Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}

So you can see the fn (your callback) will always be called with your 'this' (scope)

Hope it helps...

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.