Techie Techie - 1 year ago 115
Javascript Question

Method overloading in Javascript

I use method overloading as below in my Javascript code.

function somefunction()
//1st function

function somefunction(a)
//2nd function

function somefunction(a,b)
//3rd function

somefunction(); // function call goes here

What I don't understand is if I call the
javascript should call the 1st function but the problem is javascript actually calls the 3rd function. Why is that? How can I call the 1st and 2nd function ? What is the reason for this? Is there a proper way to implement method overloading in Javascript? What's the industry standard?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download