Currying in javascript

Jonathan

I read an example chapter from Professional JavaScript for Web Developers, 2nd Edition: Chapter 18, “Advanced Techniques” last week and the discussion about currying functions finally made sense to me as in “oh, I see how I would use that”. If you want to understand it better look at the chapter linked above.

I have been using it for callback functions that require extra arguments from the local scope, it is a lot less wordy than the method that I had been using, and I think it better conveys the meaning of what I am trying to do.

Previously I would put the following:

var someValue;
$("#someElement").click(function(e){
    clickHandler(someValue);
});

And now I put this:

var someValue;
$("#someElement").click(clickHandler.curry(someValue));

I implemented this using a method that I placed on the Function.prototype. I think that is a nicer syntax than is recommended in the book.

Function.prototype.curry = function(){
      var args = Array.prototype.slice.call(arguments);
      var fn = this;
      return function(){
          var innerArgs = Array.prototype.slice.call(arguments);
          var finalArgs = args.concat(innerArgs);
          return fn.apply(null, finalArgs);
     };
}

One Response to “Currying in javascript”

  • Gooder Code Says:

    Function currying in Javascript…

    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 p……

Leave a Reply