Array.prototype.forEever alternative implementation options

When working with my latest web application and using the Array.forEach function Array.forEach I constantly found the following code used to add support for older browsers that do not have a built-in function.

 /** * 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 that it is copied with the formal thisp parameter, commented out and setting it as a local variable instead of arguments[1] .

I was wondering if anyone knows why this change was made, because from what I can say, the code would work fine with thisp as a formal parameter and not a variable?

+4
source share
2 answers

Array.prototype.forEach.length defined as 1 , so the implementation functions would be more native if they had the .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 number of arguments that func accepts based on its definition.)

For func.length be 1 , you must define func to accept only one argument. In the function itself, you can always get all the arguments using arguments . However, by defining a function to accept 1 argument, the .length property has a value of 1 . Therefore, it is more correct in accordance with the specification.

+5
source

This will iterate over each of the values ​​in the array without iterating over the string equivalent of prototypes.

 Array.prototype.forEach = function(fun /*, thisp*/) { if (typeof fun != "function") { throw new TypeError(); } for(i = 0; i < this.length; i++){ ... } } 
-1
source

Source: https://habr.com/ru/post/1384213/


All Articles