4

在开发我最新的 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作为形式参数而不是变量可以正常工作?

4

2 回答 2

5

Array.prototype.forEach.length被定义为,因此如果实现函数也将其属性设置为,1则它们将更像本机。.length1

http://es5.github.com/#x15.4.4.18

forEach 方法的长度属性为 1。

func.lengthfunc基于其定义的参数数量。)

func.length成为1,您必须定义func只接受 1 个参数。在函数本身中,您始终可以使用arguments. 但是,通过将函数定义为采用 1 个参数,.length属性为1. 因此,根据规范更正确。

于 2011-12-01T21:34:43.970 回答
-1

这将遍历数组中的每个值,而不遍历与原型函数等效的字符串。

Array.prototype.forEach = function(fun /*, thisp*/) {
    if (typeof fun != "function") {
        throw new TypeError();
    }

    for(i = 0; i < this.length; i++){
        ...
    }

}
于 2011-12-01T21:35:40.940 回答