Array.prototype.forEach替代实现参数
当我开发最新的 Web 应用程序并需要使用 Array.forEach 函数时,我不断发现以下代码用于添加对没有内置该函数的旧版浏览器的支持。
/**
* 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]
将其设置为局部变量。
我想知道是否有人知道为什么要进行此更改,因为据我所知,使用 thisp
作为形式参数而不是变量,代码可以正常工作?
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);
}
}
};
}
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Array.prototype.forEach.length
定义为1
,因此如果设置了.length
属性,实现函数将更加原生也到1
。http://es5.github.com/#x15.4.4.18
(
func.length
是func
根据其定义采用的参数量。)对于
func.length< /code> 为
1
,您必须定义func
仅接受 1 个参数。在函数本身中,您始终可以使用arguments
获取所有参数。但是,通过将函数定义为采用 1 个参数,.length
属性为1
。因此,根据规范,它是更正确的。Array.prototype.forEach.length
is defined as1
, so implementation functions would be more native-like if they had their.length
property set to1
too.http://es5.github.com/#x15.4.4.18
(
func.length
is the amount of argument thatfunc
takes based on its definition.)For
func.length
to be1
, you have to definefunc
to only take 1 argument. In the function itself you can always get all arguments witharguments
. However, by defining the function to take 1 argument, the.length
property is1
. Therefore, it is more correct according to the specification.这将迭代数组中的每个值,而不迭代原型函数的等效字符串。
This will iterate through each of the values in the array without iterating over the string equivalent of prototype functions.