I'm reading Secrets of Javascript Ninja and came across an example that I cannot fully understand. This same example was cited by some other user here before, but their doubts are different than mine. Here is the example:
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);
};
}
This is an example of function overloading, used this way:
var ninja = {};
addMethod(ninja,'whatever',function(){ /* do something */ });
addMethod(ninja,'whatever',function(a){ /* do something else */ });
addMethod(ninja,'whatever',function(a,b){ /* yet something else */ });
I have a solid understanding of scope, closure and the use of apply(). My doubts are:
- fn.length will return the number of parameters defined in fn. Will arguments.length return the number of which arguments? The already existing function's?
- But if so, and they match, why will it then apply the NEW function and not the existing one?
- If arguments.length returns the number of the given function, then when will they be different?
- I add 10 methods, starting with no parameters and increasing the number of them each time, after adding the 10th method, I call the method with no parameters, where did it 'store' the first function?
- I don't understand the use of old here.
I probably do not have some key concept that responds to all of the questions. Feel free to give me an explanation rather than responding the questions individually.
arguments.lengthwill be the # of args passed to the closest outer function from where it's called. 2. it will apply the one with the same call signature as the method(s) you added, or else go to the last one added. 3.arguments.lengthreturns what's passed, not what's defined. 4. as old, which every methods uses closure to see. basically, it will start at the one for 10 args, and if there's not 10, then try 9, and if not 9, then try 8, all the way back to the one whose formal params matches the arguments.switch(arguments.length)to handle the routing.