John Resig has posted on JavaScript Method Overloading where he discusses the ability to run different code depending on the number of arguments passed into the same function name. The type of arguments are not considered, which is where JavaScript 2 comes in.
The code he uses:
-
-
// addMethod - By John Resig (MIT Licensed)
-
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 );
-
};
-
}
-
-
// Now setup the methods
-
-
function Users(){
-
addMethod(this, "find", function(){
-
// Find all users...
-
});
-
addMethod(this, "find", function(name){
-
// Find a user by name
-
});
-
addMethod(this, "find", function(first, last){
-
// Find a user by first and last name
-
});
-
}
-
-
// Now use the methods
-
var users = new Users();
-
users.find(); // Finds all
-
users.find("John"); // Finds users by name
-
users.find("John", "Resig"); // Finds users by first and last name
-
users.find("John", "E", "Resig"); // Does nothing
-
John ends with the caveats:
- The overloading only works for different numbers of arguments - it doesn't differentiate based on type, argument names, or anything else. (ECMAScript 4/JavaScript 2, however, will have this ability - called Multimethods - I'm quite excited.)
- All methods will some function call overhead. Thus, you'll want to take that into consideration in high performance situations.
Now, the secret sauce is all going back to the fn.length expression. This isn't very well known, but all functions have a length property on them. This property equates to the number of arguments that the function is expecting. Thus, if you define a function that accepts a single argument, it'll have a length of 1, like so:
(function(foo){}).length == 1
