Array.prototype.forEach替代实现参数 [英] Array.prototype.forEach alternative implementation parameters
问题描述
在处理我最新的Web应用程序并需要使用 Array.forEach
函数时,我经常发现以下代码用于添加对没有的旧浏览器的支持内置的功能。
When working on my latest web application and needing to use the Array.forEach
function, I constantly found the following code used to add support to older browsers that do not have the function built in.
/**
* Copyright (c) Mozilla Foundation http://www.mozilla.org/
* This code is available under the terms of the MIT License
*/
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
fun.call(thisp, this[i], i, this);
}
}
};
}
我完全理解代码的作用及其工作原理,但我总是看到它使用正式的 thisp
参数进行复制,并使用 arguments [1]
将其设置为局部变量。
I fully understand what the code does and how it works, but I always see it copied with the formal thisp
parameter commented out and having it be set as a local variable using arguments[1]
instead.
我想知道是否有人知道为什么要进行此更改,因为据我所知,代码可以正常使用 thisp
作为形式参数而不是变量?
I was wondering if anyone knew why this change was made, because from what I can tell, the code would have worked fine with thisp
as a formal parameter rather than a variable?
推荐答案
Array.prototype。 forEach.length
定义为 1
,因此如果实现函数的 .length <,则实现函数将更像本机函数/ code>属性也设置为
1
。
Array.prototype.forEach.length
is defined as 1
, so implementation functions would be more native-like if they had their .length
property set to 1
too.
http://es5.github.com/#x15.4.4.18
forEach方法的length属性为1.
The length property of the forEach method is 1.
( func.length
是am func
根据其定义获取的参数的数量。)
(func.length
is the amount of argument that func
takes based on its definition.)
对于 func.length
要 1
,你必须定义 func
才能获得1个参数。在函数本身中,您始终可以使用参数
获取所有参数。但是,通过定义取1参数的函数, .length
属性为 1
。因此,根据规范更正确。
For func.length
to be 1
, you have to define func
to only take 1 argument. In the function itself you can always get all arguments with arguments
. However, by defining the function to take 1 argument, the .length
property is 1
. Therefore, it is more correct according to the specification.
这篇关于Array.prototype.forEach替代实现参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!