Method Overloading for JavaScript
John Resig posted an article about JavaScript Method Overloading, where he provides a slick way of creating multiple versions of a method based on the number of arguments in the method signature. His method uses the original function name as a pointer to a linked list of functions. The method is called, the linked list is traversed, and the appropriate function returns.
// 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 );
};
}
Alan and I spent to time dissecting Resig’s implementation. The drawback of using a linked list of functions is that performance degrades when a large number of unique methods exist.
There’s a more scalable way to create these overloaded methods. If we use a two-dimensional lookup table (the first dimension is the method name and the second dimension is the argument length), we can overload the method 100 times without much performance degradation. So I present my own version of addMethod():
// addMethod - By G Scott Olson (Unlicensed)
function addMethod(object, name, fn){
object._methods = object._methods || {};
object._methods[name] = object._methods[name] || {};
object._methods[name][fn.length] = fn;
object[name] = function(){
if(this._methods[name][arguments.length])
return this._methods[name][arguments.length].apply(this, arguments);
};
}
An example:
function Users() {
addMethod(Users.prototype, "find", function(){/*function body*/});
addMethod(Users.prototype, "find", function(name){/*function body*/});
addMethod(Users.prototype, "find", function(first, last){/*function body*/});
}
Sorry, this discussion is closed.