Method overloading in Javascript

Solution 1:

JavaScript does not support method overloading (as in Java or similiar), your third function overwrites the previous declarations.

Instead, it supports variable arguments via the arguments object. You could do

function somefunction(a, b) {
    if (arguments.length == 0) { // a, b are undefined
        // 1st body
    } else if (arguments.length == 1) { // b is undefined
        // 2nd body
    } else if (arguments.length == 2) { // both have values
        // 3rd body
    } // else throw new SyntaxError?
}

You also could just check for typeof a == "undefined" etc, this would allow calling somefunction(undefined), where arguments.length is 1. This might allow easer calling with various parameters, e.g. when you have possibly-empty variables.

Solution 2:

JS will pass undefined to any parameters which are not provided. If you want something like overloading, you'll need to do something similar to the code below:

function someFunction(a, b) {
    if (typeof a === 'undefined') {
        // Do the 0-parameter logic
    } else if (typeof b === 'undefined') {
        // Do the 1-parameter logic
    } else {
        // Do the 2-parameter logic
    }
}

Solution 3:

You're just erasing the variable somefunction with each new declaration.

This is equivalent to

   window.somefunction = function(...
   window.somefunction = function(...
   window.somefunction = function(...

Javascript doesn't offer method overloading.

The proper way is either :

  • to define the third function and to test what parameters are defined
  • to pass only one object containing the parameters (which isn't really different but is cleaner)

Solution 4:

You can't overload methods in JavaScript. In javascript, functions are stored in variables. Global variables are stored on the window object. You can only have one property per object with the same name (exclusive-key hash).

What you can do, is define the definition with the most parameters and check to see how many were passed in.

function Test(a, b, c)
{
    if(typeof a == 'undefined') 
    {
        a = 1;
    }

    if(typeof b == 'undefined') 
    {
        b = "hi";
    }

    if(typeof c == 'undefined') 
    {
        c = Date.Now;
    }
}

Now if I call Test(), it'll act as if I called Test(1, "hi", Date.Now)

Solution 5:

There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. the best practice would be to make a function like: myfunc(opt)

{
// with opt = {'arg1':'a1','arg2':2, etc}, then check your opt inside of the function
}