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)
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With