I'm newbie in Javascript. And I faced the following question.
As stated here, almost all ES5 Array functions (forEach, map, filter, every, some) can take additional second argument.
If it specified the function is invoked as if it is a method of this second argument. That is, the second argument you pass becomes the value of the this keyword inside of the function you pass.
array.forEach(function(currentValue, index, arr), thisValue)
array.map(function(currentValue, index, arr), thisValue)
On the contrary:
array.reduce(callback, [initialValue])
array.reduceRight(callback, [initialValue])
Note that neither reduce() nor reduceRight() accepts an optional argument that specifies the this value on which the reduction function is to be invoked. See the Function.bind() method if you need your reduction function invoked as a method of a particular object.
What does it mean: "to be invoked as a method of a particular object"? Could anyone provide some example how it may affect on my code?
Thanks in advance.
It's simple. In the callback function, the
this
value will be the second argument passed to the array method. If you won't usethis
, then the argument is irrelevant and you don't need to pass it.Note that in sloppy mode, the
this
value is converted to an object. So if you omit the argument or useundefined
, you will get the global object instead.If you need something similar with
reduce
, then usebind
: