I was browsing through the JavaScript Garden when I stumbled upon the Function.call.apply hack which is used to create “fast, unbound wrappers”. It says:
Another trick is to use both call and apply together to create fast, unbound wrappers.
function Foo() {} Foo.prototype.method = function(a, b, c) { console.log(this, a, b, c); }; // Create an unbound version of "method" // It takes the parameters: this, arg1, arg2...argN Foo.method = function() { // Result: Foo.prototype.method.call(this, arg1, arg2... argN) Function.call.apply(Foo.prototype.method, arguments); };
What I don’t understand is why bother using Function.call.apply when Function.apply would suffice. After all, both of them are semantically equivalent.
No,
Function.call.applyandFunction.applyare not the same in this case.Let’s say the original caller invokes
With call and apply together, as in the JavaScript Garden code. This executes
which is (loosely, writing
argumentsin array-notation):which invokes
Function.callwiththis==Foo.prototype.method:which calls
Foo.prototype.methodwiththisset totand argumentsx,y, andz. Sweet. Just like in the comments. We have successfully made a wrapper.Now suppose you left said just
Function.applyinstead ofFunction.call.apply, which you claim is semantically equivalent. You would havewhich is (loosely)
which calls the function
Function(ugh!) withthisset toFoo.prototype.methodand argumentst,x,y, andz.Not the same at all.