Reputation: 2939
Looking for more details on what exactly is happening when following is executed:
function useArray(){
var args = [].slice.call(arguments)
console.log(args)
}
How come slice
being a function with 3 parameters (source array, start and end positions to copy) threats arguments
correctly? Method call
needs correct value of first argument as this
but it seems arguments
gets turned into Array object?
And why this doesn't work:
var args = [].slice(arguments)
Upvotes: 1
Views: 64
Reputation: 36448
We're using [].slice
to get at the Array::slice
method. arguments
doesn't have a slice()
of its own, but it is array-like.
Although it's a member of Array
, slice()
will work well enough on array-like objects -- things that have .length
and can be indexed with [0..n]
.
slice()
with no parameters returns a copy of the entire array. Its arguments are both optional.
So it's as if arguments
had a slice()
method, and we called arguments.slice()
to get a copy of it (as an array).
[].slice(arguments)
is just calling Array::slice()
on an empty array, with arguments
as the begin
parameter, which makes no sense since begin
(if present) should be a number.
Upvotes: 1