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?
Array.prototype.forEach.lengthis defined as1, so implementation functions would be more native-like if they had their.lengthproperty set to1too.http://es5.github.com/#x15.4.4.18
(
func.lengthis the amount of argument thatfunctakes based on its definition.)For
func.lengthto be1, you have to definefuncto 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.lengthproperty is1. Therefore, it is more correct according to the specification.