Javascript ES5 Array functions. forEach second “Th

2020-04-11 13:09发布

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.

1条回答
太酷不给撩
2楼-- · 2020-04-11 13:53

It's simple. In the callback function, the this value will be the second argument passed to the array method. If you won't use this, then the argument is irrelevant and you don't need to pass it.

"use strict";
[0].forEach(function(currentValue, index, arr) {
  console.log(this); // 1234
}, 1234);

Note that in sloppy mode, the this value is converted to an object. So if you omit the argument or use undefined, you will get the global object instead.

If you need something similar with reduce, then use bind:

"use strict";
[0, 1].reduce(function(prevValue, currValue, index, arr) {
  console.log(this); // 1234
}.bind(1234));

查看更多
登录 后发表回答