1

I have included two .js files in my jsp file.
Each file has function named getOrderType but one takes single argument while other takes 3.The one with 3 arguments function is imported first.When the function is called on 'onclick' event with three parameters,still the single parameter function gets called.
As I think,is it due to order of importing files?If not,how do I resolve the conflict? On changing sequence of imports the conflict goes but I still want full proof solution

JG1991
  • 143
  • 3
  • 14
  • In JavaScript, You can just have one implementation of your function. Read [Function overloading in Javascript - Best practices](http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices) – Satpal Apr 13 '15 at 06:31
  • 1
    wrap the functions in separate objects or classes... e.g. Module1.getOrderType, Module2.getOrderType this way you can invoke both the functions as per your need.... – gp. Apr 13 '15 at 06:35

3 Answers3

2

In JavaScript, functions do not have polymorphic behaviour this way, if you want to achieve something similiar, you have to implement dispatching yourself, similiar to this:

function a(x,y,z) {
    typeof(z) == 'undefined' ? b(x,y) : c(x,y,z);
}
meskobalazs
  • 15,741
  • 2
  • 40
  • 63
0

In JavaScript you can't have various functions depends on arguments, but you can store reference to function and take decision depends on arguments length:

var f1 = (function sum(a, b, c) {
    console.log('f1 function called');
    console.log(arguments.length); // 3
});

var f2 = (function sum(a) {
    console.log('f2 function called');   
    console.log(arguments.length); // 1
});

function manager(a, b, c) {
    if(arguments.length == 3) {
        return f1(a, b, c);   
    }
    if(arguments.length == 1) {
        return f2(a);   
    }
}

manager(1, 2, 3);  // f2 function called
manager(4);  // f1 function called
Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88
0

Sure. There is no way to overload a function. You may remember it as native to the language, it is a limitation.

ditmark12
  • 111
  • 1
  • 11