Reputation: 7792
So I'm reading through a book and it uses this method to overload functions-
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);
}
}
}
I have a few questions on this.
Upvotes: 1
Views: 112
Reputation: 413720
arguments
object. If it sees that the number of arguments passed is the same as the number of formal parameters in the "fn" function, then it calls that function. Otherwise, it calls the previous ("old") function, if it exists and is a function..length
property of a function instance gives you the number of formal parameters in the declaration. For example, the .length
for that "addMethod" function would be 3
.The way that closures work in JavaScript took me a while to really "get" because I was a C programmer for a long time. In languages like that, space for the function call local variables (etc) is allocated on the stack, and when the function exits it's all popped off the stack. JavaScript just doesn't work that way.
Upvotes: 2