I read Jhon resig post about function overloading:
http://ejohn.org/blog/javascript-method-overloading/
The functions:
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
});
}
// 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 );
};
}
I understand the concept. The one thing I can’t understand is why each time the else if statement is executing the return old.apply(this, arguments) the arguments length is decremented by one.
I used alerts to follow the function and that is the main thing I can’t understand.
Any assistance will be appreciated.
It effectively results in a chain of
oldfunctions that are called one after the other until one whose arity matchedarguments.lengthis found. So on the first call toaddMethod, you’ll end up witholdbeingundefined.The 2nd time you call
addMethod,oldwill end up being the function that was assigned in during the first call.If you run this:
It will look for a property of
userswith the identifierfind. It will find one, and the arity of that function will be 2 (because the final call toaddMethodin the constructor creates a method that expects 2 arguments). So instead of calling that, it callsold, which will be the version of the method that expects 1 argument. Our invocation has a single argument, and that matches, so that’s the method that gets executed.If you run this:
It will do exactly what I described above, but when it calls
oldthe arity will not match and it will calloldagain. The value ofoldin this situation will be what it was after the first call toaddMethod(that’s a demonstration of a thing usually referred to as a closure – the oldoldfunction is still available after the parent function has returned).