Question

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?

Was it helpful?

Solution

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

The length property of the forEach method is 1.

(func.length is the amount of argument that func takes based on its definition.)

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.

OTHER TIPS

This will iterate through each of the values in the array without iterating over the string equivalent of prototype functions.

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

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top