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)
?
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)
?
-
1
Why not simply try calling
arguments.slice()
...? – deceze ♦ Commented Sep 15, 2015 at 15:05 -
@deceze he he :) I was so damn sure that
arguments
is an array! – sabithpocker Commented Sep 15, 2015 at 15:06
2 Answers
Reset to default 12arguments
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.
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 ma delimited values.