I've just been looking over some photos from this year's ng-europe conference and noticed a slide I think might show some code from the upcoming Angular 2. See here:
(Source: https://plus.google.com/u/0/photos/+ThierryLAU/albums/6073085583895256529/6073092865671487010?pid=6073092865671487010&oid=105910465983441810901)
Why is the author of this code using Array.prototype.forEach.call(array, cb)
in preference to the shorter and (in my opinion) equivalent version array.forEach(cb)
. The only reason I could imagine would be performance implications.
Does anybody know of another difference? Or am I maybe right with my performance guess?
There are number of Array-like objects which look like arrays, however are not. To name some:
arguments
children
and childNodes
collectionsdocument.getElementsByClassName
and document.querySelectorAll
Many array prototype methods are generic by purpose, which means that their internal implementation does not depend on context this
to be an instance of Array
constructor. This allows to call those methods in the context of other objects which "look" like arrays. Namely, looking like an array means that the object have numeric keys and length property.
Here is one useless example of how you can call Array.prototype.join
on custom array-like object:
Array.prototype.join.call({0: 'one', 1: 'two', length: 2}, ' ');
Above will output string "one two"
. However supplied object is clearly not an array.
It is being a bit defensive against element.attributes
or element.children
not being arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With