I'm currently studying Secrets of the JavaScript Ninja by John Resig and I'm hoping someone can help me further understand one of the examples.
It is a function that allows method overloading on an object, each overload has it's own definition and behaviour. He blogged about it here.
The code looks like this:
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);
};
And used like this:
addMethod(obj,'funcName',function(){});
addMethod(obj,'funcName',function(a){});
addMethod(obj,'funcName',function(a,b){});
I think I understand most of how this works but you can get a better explanation than I can give from the blog post above).
However, it accesses the value of old
and fn
using closures, which I'm still studying.
EDIT - added jsFiddle
below.
When trying to understand it, I realised that the line return fn.apply(this, arguments)
could be simply return fn()
with what seems to be the same result. See an example in this jsFiddle.
So, Why is it using the apply
syntax if not required?
I have tried playing with the example in jsFiddle without apply and it always seems to wo
Also, what exactly is happening when we return those functions, especially in the case of:
return old.apply(this, arguments);
I really want to get a solid understanding of not just how to use this method but why it works so any insight would be greatly appreciated.
Thanks