Array.prototype.forEach替代实现参数

Jos*_*hua 4 javascript ecmascript-5

在处理我最新的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);
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

我完全理解代码的作用以及它是如何工作的,但是我总是看到它被复制,并且正式thisp参数被注释掉并将其设置为使用的局部变量arguments[1].

我想知道是否有人知道为什么要做出这种改变,因为从我所知道的,代码可以thisp作为一个正式参数而不是变量工作得很好?

pim*_*vdb 5

Array.prototype.forEach.length被定义为1,所以如果实现函数的.length属性设置1也是更原生的.

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

forEach方法的length属性为1.

(func.lengthfunc基于其定义所采用的参数量.)

为了func.length做到这一点1,你必须定义func只接受1个参数.在函数本身中,您始终可以获取所有参数arguments.但是,通过定义取1参数的函数,.length属性为1.因此,根据规范更正确.