i look for this piece of code in an example that should create functions at object by name. as i understand it also can create overload of the same function on the object.
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);
};
}
so If creating a new object like
var ninja = {};
and than adding functions like:
addMethod(ninja,'whatever',function(){ /* do something */ });
addMethod(ninja,'whatever',function(a){ /* do something else */ });
addMethod(ninja,'whatever',function(a,b){ /* yet something else */ });
the object should contain 3 overload of the whatever function.
the problem I don't understand addMethod function:
I understand that we store the last function in old. do we create a closure this way? with the anonymous function?
so for executing this line of code:
else if (typeof old == 'function')
return old.apply(this, arguments);
it will recursively call all the functions defined earlier until match?
can someone explain?
thanks