I’v come across both ways to apply Array prototypes to a native object:
arr = Array.prototype.slice.call(obj);
arr = [].slice.call(obj);
In similar fashion, getting the true type of a native array-like object:
type = Object.prototype.toString.call(obj);
type = {}.toString.call(obj);
A simple test:
function fn() {
console.log(
Array.prototype.slice.call(arguments),
[].slice.call(arguments),
Object.prototype.toString.call(arguments),
{}.toString.call(arguments)
);
}
fn(0,1);
Fiddle: http://jsfiddle.net/PhdmN/
They seem identical to me; the first syntax is used more often, but the second is definitely shorter. Are there any shortcomings when using the shorter syntax?
They are identical regarding functionality.
However, the
Arrayobject can be overwritten, causing the first method to fail.The literal method creates a new instance of
Array(opposed toArray.prototype.method). Benchmark of both methods: http://jsperf.com/bbarr-new-array-vs-literal/3When you’re going to use the method many times, the best practice is to cache the method:
var slice = Array.prototype.slice; //Commonly usedvar slice = [].slice;– If you’re concerned about the existence ofArray, or if you just like the shorter syntax.