Javascript ES5数组函数。 forEach second" This Value"争论

时间:2017-01-15 17:35:13

标签: javascript arrays scope

我是Javascript中的新手。我遇到了以下问题。

如上所述here,几乎所有ES5数组函数(forEach,map,filter,every,some)都可以采用额外的第二个参数。

  

如果指定调用该函数,就好像它是第二个参数的方法一样。也就是说,您传递的第二个参数将成为您传递的函数中 this 关键字的值。

array.forEach(function(currentValue, index, arr), thisValue)
array.map(function(currentValue, index, arr), thisValue)

恰恰相反:

array.reduce(callback, [initialValue])
array.reduceRight(callback, [initialValue])
  

请注意,reduce()和reduceRight()都不接受可选参数,该参数指定要在其上调用缩减函数的this值。如果您需要将调用作为特定对象的方法,请参阅 Function.bind()方法。

这是什么意思:"被调用作为特定对象的方法"?任何人都可以举例说明它对我的代码有何影响吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

很简单。在回调函数中,this值将是传递给数组方法的第二个参数。如果你不能使用this,那么这个论点是无关紧要的,你也不需要传递它。



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




请注意,在草率模式下,this值将转换为对象。因此,如果省略参数或使用undefined,您将获得全局对象。

如果您需要与reduce类似的内容,请使用bind



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