Function currying in Javascript
- by kerry
Do you catch yourself doing something like this often?
1: Ajax.request('/my/url', {'myParam': paramVal}, function() { myCallback(paramVal); });
Creating a function which calls another function asynchronously is a bad idea because the value of paramVal may change before it is called. Enter the curry function:
1: Function.prototype.curry = function(scope) {
2: var args = [];
3: for (var i=1, len = arguments.length; i < len; ++i) {
4: args.push(arguments[i]);
5: }
6: var m = this;
7: return function() {
8: m.apply(scope, args);
9: };
10: }
This function creates a wrapper around the function and ‘locks in’ the method parameters. The first parameter is the scope of the function call (usually this or window). Any remaining parameters will be passed to the method call. Using the curry method the above call changes to:
1: Ajax.request('/my/url', {'myParam': paramVal}, myCallback.curry(window,paramVal));
Remember when passing objects to the curry method that the objects members may still change.