Why is the slice method of an array called using a "call"?

As seen in this SO question

Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; 

In this example, why is it encoded as

 args = Array.prototype.slice.call(arguments) 

will it be ok if i do

 args = arguments.slice(); 

I'm just trying to figure out any specific reason for using call

And also what will be the other scenario where we will need to use Array.prototype.slice.call(arguments) ?

+5
source share
2 answers

arguments is an array-like object; it is not an Array . Thus, it does not have a slice method. You need to execute the slice implementation from Array and invoke its configuration in the context of this on arguments . This will return the actual Array , which is the whole point of this operation.

+12
source

arguments not an array:

 function a(){console.log(typeof(arguments)) } 

So this a(123) will give object

So, we borrow a method that can deal with an array like an object in order to truncate an object as if it were a true array.

Borrowing can be done via call or apply .

apply will send the arguments as an array (remember: a for array ) - while call will send the parameters as comma-separated values.

+6
source

All Articles