MLNTN

Maniacal musings of a pixel perfectionist

Method overloading

Posted by Jared on December 4, 2007

John Resig, one of my heroes and creator of the jQuery JavaScript library, wrote a great piece about overloading methods. He created a dead simple function that shoulders most of the work. Check it out:

function addMethod(object, name, fn){
  var old = object[ name ];
  object[ name ] = function(){
    if ( fn.length == arguments.length )
      return fn.apply( this, arguments );
    else if ( typeof old == 'function' )
      return old.apply( this, arguments );
  };
}

Here’s how you could use it to extend the User object that we created earlier.

addMethod(User.prototype, "find", function(){
  // Find all users...
});
addMethod(User.prototype, "find", function(name){
  // Find a user by name
});
addMethod(User.prototype, "find", function(first, last){
  // Find a user by first and last name
});

You can read more from John’s blog here.

One Response to “Method overloading”

Leave a Reply