Why Calling Array.prototype.forEach.call() With An Array Set To THIS Object Not Working
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.
If a
thisArg
parameter is provided toforEach()
, it will be passed tocallback
when invoked, for use as itsthis
value. Otherwise, the valueundefined
will be passed for use as itsthis
value. Thethis
value ultimately observable bycallback
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"