Tuesday, April 9, 2013

how does Array.prototype.slice.call() work?



I know it is used to make arguments a real array, but I don't understand what happens when usingprototype.slice.call(arguments)
share|edit

8 Answers


up vote74down voteaccepted
What happens under the hood is that when .slice() is called normally, this is an Array, and then it just iterates the Array, and does its work.
How is this in the .slice() function an Array? Because when you do:
object.method();
...the object automatically becomes the value of this in the method(). So with:
[1,2,3].slice()
...the [1,2,3] Array is set as the value of this in .slice().

But what if you could substitute something else as the this value? As long as whatever you substitute has a numeric .length property, and a bunch of properties that are numeric indices, it should work. This type of object is often called an array-like object.
The .call() and .apply() methods let you manually set the value of this in a function. So if we set the value of this in .slice() to an array-like object.slice() will just assume it's working with an Array, and will do its thing.
Take this plain object as an example.
var my_object = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    length: 5
};
This is obviously not an Array, but if you can set it as the this value of .slice(), then it will just work, because it looks enough like an Array for .slice() to work properly.
var sliced = Array.prototype.slice.call( my_object, 3 );
As you can see in the console, the result is what we expect:
['three','four'];
So this is what happens when you set an arguments object is the this value of .slice(). Because arguments has a .length property and a bunch of numeric indices, .slice() just goes about its work as though it was working with an Array.
share|edit
2
This explanation has done more to deepen my understanding of javascript than anything I have ever read. – user1167442 Mar 5 at 13:31
Excellent explanation. You made so many other things clear too! – berto77 Mar 25 at 17:25

I'm just writing this to remind myself...
    Array.prototype.slice.call(arguments);
==  Array.prototype.slice(arguments[1], arguments[2], arguments[3], ...)
==  [ arguments[1], arguments[2], arguments[3], ... ]
Or just use this handy function $A to turn most things into an array.
function hasArrayNature(a) {
    return !!a && (typeof a == "object" || typeof a == "function") && "length" in a && !("setInterval" in a) && (Object.prototype.toString.call(a) === "[object Array]" || "callee" in a || "item" in a);
}

function $A(b) {
    if (!hasArrayNature(b)) return [ b ];
    if (b.item) {
        var a = b.length, c = new Array(a);
        while (a--) c[a] = b[a];
        return c;
    }
    return Array.prototype.slice.call(b);
}
example usage...
function test() {
    $A( arguments ).forEach( function(arg) {
        console.log("Argument: " + arg);
    });
}
share|edit

Dont forget, that a low-level basics of this behaviour is the type-casting that integrated in JS-engine entirely.
Slice just takes object (thanks to existing arguments.length property) and returns array-object casted after doing all operations on that.
The same logics you can test if you try to treat String-method with an INT-value:
String.prototype.bold.call(11);  // returns "<b>11</b>"
And that explains statement above.
share|edit

The arguments object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.
Arrays do have this method, and because the arguments object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.
So why use Array.prototype? The Array is the object which we create new arrays from (new Array()), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype object. So, for efficiency sake, instead of accessing the slice method by new Array().slice.call() or [].slice.call(), we just get it straight from the prototype. This is so we don't have to initialise a new array.
But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.
share|edit
You may want to use a slice for reasons described here: jspatterns.com/arguments-considered-harmful – KooiInc Aug 14 '11 at 13:45

Its because, as MDN notes
The arguments object is not an array. It is similar to an array, but does not have any array properties except length. For example, it does not have the pop method. However it can be converted to a real array:
Here we are calling slice on the native object Array and not on its implementation and thats why the extra .prototype
var args = Array.prototype.slice.call(arguments);
share|edit

Let's assume you have: function.apply(thisArg, argArray )
The apply method invokes a function, passing in the object that will be bound to this and an optional array of arguments.
The slice() method selects a part of an array, and returns the new array.
So when you call Array.prototype.slice.apply(arguments, [0]) the array slice method is invoked (bind) on arguments.
share|edit

Normally, calling
var b = a.slice();
will copy the array a into b. However, we can't do
var a = arguments.slice();
because arguments isn't a real array, and doesn't have slice as a method.Array.prototype.slice is the slice function for arrays, and call runs the function with thisset to arguments.
share|edit
thanx but why use prototype? isn't slice a native Array method? – IlyaD Aug 14 '11 at 13:08
Note that Array is a constructor function, and the corresponding "class" is Array.prototype. You can also use [].slice – Pumbaa80 Aug 14 '11 at 13:13
IlyaD, slice is a method of each Array instance, but not the Array constructor function. You useprototype to access methods of a constructor's theoretical instances. – Delan Azabani Aug 14 '11 at 13:16

It uses the slice method arrays have and calls it with its this being the arguments object. This means it calls it as if you did arguments.slice() assuming arguments had such a method.
Creating a slice without any arguments will simply take all elements - so it simply copies the elements from arguments to an array.
share|edit

No comments:

Post a Comment