5

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) ?

2
  • 1
    Why not simply try calling arguments.slice()...? Commented Sep 15, 2015 at 15:05
  • @deceze he he :) I was so damn sure that arguments is an array! Commented Sep 15, 2015 at 15:06

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.