Hi guys,
can you please explain how this code is working i'm a bit confuse about the fn.length == arguments.length here the code
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function(){
if (fn.length == arguments.length){ //this line i don't understand how it works
return fn.apply(this, arguments)
}else if (typeof old == 'function'){
return old.apply(this, arguments);
}
};
}
var ninjas = {
values: ["Dean Edwards", "Sam Stephenson", "Alex Russell"]
};
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.indexOf(name) == 0)
ret.push(this.values);
return ret;
});
addMethod(ninjas, "find", function(first, last){
var ret = [];
for (var i = 0; i < this.values.length; i++)
if (this.values == (first + " " + last))
ret.push(this.values);
return ret;
});
when you call addMethod the first time fn.length == arguments.length is true both are zero that's fine then it execute return fn.apply(this, arguments)
the second and third fn.length is 1 then 2 but arguments.length is 0 because no args passed to the anonymous function and it should execute return old.apply(this, arguments); but what happened it execute the first condition so how comes it execute this line even if the lengths are not equal