Reputation: 2643
Why would you slice an array like this:
Array.prototype.slice.call(arr, 3);
Instead of simply:
arr.slice(3);
?
What are the benefits of using the prototype and the call?
Thanks!
Upvotes: 3
Views: 304
Reputation: 413757
The key benefits are realized when "arr" is not an array, but something like an array; specifically, something with a "length" property and numerically-keyed properties. Good examples are the arguments
object and NodeList objects from a DOM. Those things won't have a "slice" method, but they do have numerically-keyed properties and a "length" property.
The trick works because the "slice" method is pretty forgiving.
If you see it being used with something that's definitely an array already, then you're looking at code written by a confused person :)
Oh, and note also that a short-cut is:
var foo = [].slice.call(arguments, 0);
You don't have to go to the prototype directly if you don't want to; you can get at it from an array instance just as easily. (Yes, it costs a dummy allocation, but in this day and age I wouldn't be surprised if VMs optimized that away.)
Upvotes: 6