I'm reading a book called "Secrets of the JavaScript Ninja" and in it, I came across a method overload function. So far so good, I understood what it does, I understand that it 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 in the console the ninjas.find()
method it will return the complete Array of the values
property of the ninjas
object, if it calls something like ninjas.find("Dean")
, only the name corresponding to the search will be returned. >
My question is this: When we make the second assignment of the function find
through addMethod()
, why does not it overwrite the previous one? Or rather, I want to understand what is happening so that the two find
functions can exist simultaneously.