Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, guys, this is my first time here and I've been reading the book by John Resig - Secrets of the Javascript Ninja. I have come across the addMethod function that takes in 3 parameters and helps with function overloading. I am familiar with function overloading but i don't understand how this function works, it is small but complex.
JavaScript
function addMethod(object, name, fn)
{
    var old = object[name];
    object[name] = function()
    {
        if( fn.length == arguments.length )
        {
            return fn.apply(this, arguments);
        }
        else if
        {
            return old.apply(this, arguments);
        }
    }
}

// object - object to be acted on
// name - name of the function, i presume
// fn - callback function, i presume

Now I don't understand how this function is working, it can't work without the if and else if statements, i tried and i get 'undefined' in the console.

Please explain how the function works.
Posted
v2

1 solution

It is explained here[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900