I'm currently reading about JavaScript closures and have come across an example in the book that is really bothering me. In all honesty, I'll probably never need to understand this example or at least not any time soon. But its just one of those annoying things that is going to keep me up at night thinking about it.
Anyway, the book I'm reading below lists the following function that returns a function that invokes the function 'f' with the specified arguments and also any additional arguments that are passed to the returned function. (confused yet?)
My issue is with why "f.apply(this,args)" works, but if I change it to "f(args)" it no longer works. I wrote the following code to test the function above, and sure enough it works as is but not if I change to "f(args)".Code:function bindArguments(f /*, initial arguments */) { var boundArgs = arguments; return function() { var args = []; for(var i=1; i < boundArgs.length; i++) args.push(boundArgs[i]); for(var i=0; i < arguments.length; i++) args.push(arguments[i]); return f.apply(this,args); // why doesn't f(args) work here } }
I understand what the apply method is - at least how to use it to call a regular function as a method of an object, but I can't understand its purpose here or why it fails without it. Any insights would be greatly appreciated.Code:function count() { var total = 0; for(var i=0; i < arguments.length; i++) total = total + arguments[i]; return total; } var func = bindArguments(count,1,2); var sum = func(3,4); document.write("sum: " + sum + "<br/>");








Bookmarks