How can implement overloading in JavaScript/jQuery?

mattn has the correct idea. Because javascript has no typing those functions are equivalent. What you could do is something like this:

function OpenBox_impl1(obj1,obj2){
    // code
}
function OpenBox_impl2(obj1,obj2,obj3,obj4,obj5){
    // code
}

function OpenBox(obj1, obj2, obj3, obj4, obj5) {
    if(arguments.length == 2)
        return OpenBox_impl1(obj1, obj2);
    else
        return OpenBox_impl2(obj1,obj2,obj3,obj4,obj5);
}

javascript can't define duplicate function in same scope. check arguments.length are 2 or 5.


You cannot overload functions in JavaScript. Instead, the most recently defined version of the function will be used, which is why in your case the version with 5 parameters is called (the final 3 are just undefined).

There are several ways around this, one if which is shown in Mikola's answer. An alternative is to pass in an object, and then check the contents of that object in the function (see this question):

function foo(a, b, opts) {

}

foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});

Another option is to check arguments.length:

function foo(a, b) {
    if(arguments.length > 2) {
        var arg3 = arguments[3];
        //etc...
    }
}

in the polymorphism you can use a different signature method ,in javascript we can simulate polymorphism checking the type of the function parameter and execute certain task.

var input = document.getElementById('data');
polymorphism(input);
polymorphism('Hello word 2');
polymorphism('hello word 3', 5);

function polymorphism(arg,arg1){ 
  var string = null;
  var sqr = 0;
  if(typeof arg === 'string'){
    string = 'arg type String: \n'+arg;
  }else if (arg.tagName && arg.tagName === 'INPUT'){
    string = 'arg type Input: \n'+arg.value;
  }
  if(arg1 && typeof arg1 === 'number'){
    sqr = arg1*arg1;
    alert(string + ' and sqr = '+sqr);
  }else {
    alert(string);
  }    
}

Check this example in JSFIDDLE