Possible Duplicate:
What’s the meaning to chain call and apply together?
I found some codes like this:
function fun() {
return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
I know the call and apply in js,however I am confused when they come together.
Then I wonder if
Function.prototype.call.apply(Array.prototype.slice, arguments)
is the same as :
Array.prototype.slice.apply(arguments);
If not,what does the first line do?
Alright, let’s tackle this problem via substitution. We start with:
What we know:
Function.prototype.callis a function.thispointer ofcallpoints toFunction.prototype.applyto change thethispointer ofcalltoArray.prototype.slice.argumentsis applied (not passed as a parameter) tocall.Thus the above statement is equivalent to:
From this we see:
Array.prototype.sliceis a function.thispointer ofslicepoints toArray.prototype.callto change thethispointer ofslicetoarguments[0].arguments[1], ...are passed as parameters toslice.This is the same as:
The advantage of this is that we’re creating a fast unbound wrapper for
slicein a single line.Edit: A better way to create fast unbound wrappers is as follows (note that it may not work in some older browsers, but you don’t really need to worry about that now – you may always use a shim for browsers which don’t support
bind):This is the same as:
How it works:
Function.prototype.callis a function.thispointer ofcallpoints toFunction.prototype.bindto change thethispointer ofcalltoArray.prototype.slice.bindreturns a function whoseargumentsare applied tocall.Bonus: If your style of programming is highly functional, like mine is, then you would find that is piece of code is very useful:
callorapply.classOfto get the internal[[Class]]of a value.ownPropertyOfinside for in loops.concatenateto join arrays.arrayFromto create arrays.