JAVASCRIPT: Method overloading


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:

1
2
3
4
5
6
7
8
9
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.

1
2
3
4
5
6
7
8
9
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.

Information and Links

Join the community by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
LEARNING: 2008 monthly plan
JAVASCRIPT: Creating objects and methods

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Spiffy.