4
I’m reading a book called "Secrets of Ninja Javascript" and in it, I came across a method overload function. So far so good, I understood what she does, I understood that she makes depending on the amount of parameters passed to the function a different method will be called.
The function that appears in the book is as follows:
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);
};
}
var ninjas = {
values : ["Dean Edwards", "Sam Stephenson", "Alex Russel"]
};
addMethod(ninjas, "find", function(){
return this.values;
});
addMethod(ninjas, "find", function(name){
var ret = [];
for (var i =0; i < this.values.length; i++)
if(this.values[i].indexOf(name) == 0)
ret.push(this.values[i]);
return ret;
});
If you call on your console the method ninjas.find() it will return the full Array of the property values of the object ninjas, if you call something like ninjas.find("Dean"), only the name corresponding to the query will be returned.
My question is this: When we do the second assignment of the function find by means of addMethod(), Why doesn’t she overwrite the previous one? Or rather, I want to understand what is happening so that the two functions find may exist simultaneously.

I think you have overwritten (with addMethod) the method without parameters. When you call the method with parameters, the called method is what already existed not what you injected.
– RSinohara
Yes, but if after calling the method with parameters you call the no parameters, it is still there
– Lucas Muller