Kaeros
Kaeros

Reputation: 1138

Understanding the use of slice in function arguments

I was reading this piece of code from the mozilla developer network:

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

The line inside the function confused me, why can i use call without specifying an object to serve as this?

If the arguments is the this is this case, then i'm not passing any parameter to the slice function, right?

If i put some random element as this i get an empty array, like this:

return Array.prototype.slice.call([], arguments);

I know i misunderstood something, but what? :)

Thanks in advance!

Upvotes: 0

Views: 67

Answers (2)

Eric
Eric

Reputation: 97571

slice returns a copy of the entire array when called with no arguments

> x = [1, 2, 3]
> x.slice()
[1, 2, 3]
> x.slice() == x
false

In your example, this is done to convert the arguments pseudo-array into a true array.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359786

If the arguments is the this is this case

...which it is

then i'm not passing any parameter to the slice function, right?

correct.

Upvotes: 4

Related Questions