Skip to content Skip to sidebar Skip to footer

Why Calling Array.prototype.forEach.call() With An Array Set To THIS Object Not Working

Here I have a number array. I tried to test if Array.prototype.forEach can be used on array in a different way than the traditional way. In traditional way we pass the THIS argumen

Solution 1:

Because assuming forEach has not been overwritten, and this array still has the normal prototype, this:

Array.prototype.forEach.call(number,function(elem){ });

Is no different from:

number.forEach(function(elem){ });

In a forEach callback function, unless you pass the thisArg, the function is called like a normal callback.

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.

To set the thisArg while using .call, you would need to pass one more argument:

Array.prototype.forEach.call(number,function(elem){ }, number);

Solution 2:

According to 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.

In the following snippet, we explicitly pass as the thisArg the number and we have as result that you are looking for.

number=[1,2,3,4,5];

Array.prototype.forEach.call(number,function(elem){
    console.log(this);
},number);

Post a Comment for "Why Calling Array.prototype.forEach.call() With An Array Set To THIS Object Not Working"