简体   繁体   English

Javascript ES5数组函数。 forEach第二个“这个价值”的论点

[英]Javascript ES5 Array functions. forEach second “This Value” argument

I'm newbie in Javascript. 我是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. 如前所述这里 ,几乎所有的ES5阵列功能(的forEach,地图,过滤器,每一个,一些)可以采取额外的第二个参数。

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. 也就是说,您传递的第二个参数将成为您传递的函数内this关键字的值。

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. 请注意,reduce()和reduceRight()都不接受可选参数,该参数指定要在其上调用缩减函数的this值。 See the Function.bind() method if you need your reduction function invoked as a method of a particular object. 如果需要调用约简函数作为特定对象的方法,请参见Function.bind()方法

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. 在回调函数中, this值将是传递给数组方法的第二个参数。 If you won't use this , then the argument is irrelevant and you don't need to pass it. 如果你不使用this ,那么参数是无关紧要的,你不需要传递它。

 "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. 请注意,在草率模式下, this值将转换为对象。 So if you omit the argument or use undefined , you will get the global object instead. 因此,如果省略参数或使用undefined ,您将获得全局对象。

If you need something similar with reduce , then use bind : 如果你需要类似于reduce东西,那么使用bind

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM