3

I have two JavaScript functions with same name but different function definition (one is parameter less and other one with two parameters). When I try to invoke parameter less function from code-behind, it always call parameterized function. But when i remove paramterized function then the function with no parameters is getting invoked. I want to know why this happening:

e.g;

<script>
function A()
{
  alert(1);
}
function A(param1 , param2)
{
  alert(2);
}
</script>

from code-behind:

Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "A()", true);

Result: aler(2);

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Haider
  • 133
  • 3
  • 10

4 Answers4

5

JavaScript doesn't support having two functions with the same name and different parameters. Since everything is an object only the name matters. Parameters are just metadata for the function.

You will have to have different names for those functions for this to work.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
  • 1
    _You will have to have different names_ i don't think so. there are if checks and switch cases too. – Jai Feb 28 '17 at 07:09
  • 1
    @Jai And they won't help at all with calling a different function. Sure, you can make a function that checks which function you want to call, but that's kinda pointless when you can just call the actual function directly... – Sami Kuhmonen Feb 28 '17 at 07:15
0

Function overloading is not supported in Javascript.

Refer the accepted answer of this Stack Overflow question which might help you.

Community
  • 1
  • 1
Sandesh Gupta
  • 1,175
  • 2
  • 11
  • 19
0

If you want to achieve function overloading in JavaScript, you can use the arguments object that every function in JavaScript has. An arguments object is nothing but an array like object that contains the arguments/parameters passed to the function. You might have to change the approach a bit though.

Try this:

function A() {
    if(arguments.length === 1) {
        // code for one argument goes here
    }
    if(arguments.length === 2) {
        // code for two arguments goes here
    }
    // your further logic if needed
}

Now you can call your function A with different parameters, like so:

A(1); // code for arguments.length === 1 gets executed
A(1, 2); // code for arguments.length === 2 gets executed

Note: This is not exactly function overloading, but instead tries to work around a way of not having one.

Hope this helps.

0

Actually, the real behavior is - Javascript will override all previously written functions with same names(even if they have different no/type of parameters) with the last function. So, whatever parameters you provide in function call - it will always be the last function which will be called.

Kapil Raghuwanshi
  • 867
  • 1
  • 13
  • 22