methodize

someFunction.methodize() -> Function

Takes a function and wraps it in another function that, at call time, pushes this to the original function as the first argument.

The methodize method transforms the original function that has an explicit first argument to a function that passes this (the current context) as an implicit first argument at call time. It is useful when we want to transform a function that takes an object to a method of that object or its prototype, shortening its signature by one argument.

Examples

// start off with a simple function that does an operation
// on the target object:
var fn = function(target, foo) {
  target.value = foo;
};

var object = {};

// use the original function
fn(object, 'bar');
object.value //-> 'bar'

// if we methodize it and copy over to the object, it becomes
// a method of the object and takes 1 argument less:
object.fnMethodized = fn.methodize();
object.fnMethodized('boom!');
object.value //-> 'boom!'

Of course, usage shown in the example is rarely useful. It's more useful to copy methodized functions to object prototypes so that new methods are immediately shared among instances. In Prototype library, methodize has important usage in DOM and Event modules; Element.Methods and Event.Methods are methodized and placed in their native prototypes so that they are available on DOM nodes and event objects, respectively.