Alex Rivera | Logout

Difference between Array.slice and Array().slice

Asked 2008-09-23T12:54:41.823
27

I am going through John Resig's excellent Advanced javascript tutorial and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)

>>> arguments  
[3, 1, 2, 3]  
>>> Array.slice.call( arguments )  
3,1,2,3 0=3 1=1 2=2 3=3  
>>> Array.slice.call( arguments, 1 )  
[]
>>> Array().slice.call( arguments )  
3,1,2,3 0=3 1=1 2=2 3=3  
>>> Array().slice.call( arguments, 1 )  
1,2,3 0=1 1=2 2=3  

Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).

Edit
Report

3 Answers

39

Not quite.

Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2):

>>> String.substring.call("foo", 1)
"1"

>>> String().substring.call("foo", 1)
"oo"

Array.slice is neither properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).

The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. Try running the equivalent code in IE and you'll get an error that Array.slice is null.

This is why Array.slice does not behave correctly (nor does String.substring).

Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):

>>> Array.slice.call([1,2], [3,4])
3,4

Now, if you properly call slice() on either an instantiated object or the Array prototype, you'll get what you expect:

>>> Array.prototype.slice.call([4,5], 1)
[5]
>>> Array().slice.call([4,5], 1)
[5]

More proof...

>>> Array.prototype.slice == Array().slice
true
>>> Array.slice == Array().slice
false
answered 2008-09-23T14:22:51.487
-1

Well,

Looking at http://www.devguru.com/Technologies/ecmascript/quickref/slice.html

Array().slice is a function (constructor)in the array class, It cant be used as a data member. If you didn't want to use the '()' you would need to call it on the array. ie - arguments.slice(1)

answered 2008-09-23T13:42:46.560
-1

My guess is that Array is a prototype while Array() is an actual array object. Depending on the JavaScript interpretation, directly calling the prototype method of a builtin object type might work or it might not. I don't believe the spec says it has to work, just that calling it on a instantiated object works.

answered 2008-09-23T13:43:31.673

Your Answer