Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is array slice method called using "call"?

Tags:

javascript

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 coded as

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

will it be ok if I do

args = arguments.slice();

I am just trying to understand any specific reason for using call

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

like image 306
sabithpocker Avatar asked Sep 15 '15 15:09

sabithpocker


2 Answers

arguments is an array-like object, it is not an Array. As such, it doesn't have the slice method. You need to take the slice implementation from Array and call it setting its this context to arguments. This will return an actual Array, which is the whole point of this operation.

like image 52
deceze Avatar answered Sep 24 '22 17:09

deceze


arguments is not an array :

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

So this a(123) will yield object

So we borrow the method which can deal with array like object , to slice the object for as as if it was true array.

Borrowing can be made via call or apply.

apply will send arguments as an array ( remember : a for array) - while call will send params as comma delimited values.

like image 24
Royi Namir Avatar answered Sep 22 '22 17:09

Royi Namir