jump to navigation

Javascript function overloading November 28, 2008

Posted by venkatworld in Uncategorized.
Tags: ,
trackback

JavaScript function overloading..!

 

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head >

    <title>Javascript Function calls.</title>

<script language=”javascript” type=”text/javascript” >

     

    function Add()

    {

      alert(‘Add With No Parameters ‘);

    }

   

    function Add(val1,val2)

    {

      alert(‘Add With Two Parameters ‘+(val1+val2));

    }

    function Add(val1)

    {

      alert(‘Add With one Parameter ‘+val1);

    }

 

    function Add(val1,val2,val3)

    {

      alert(‘Add With Three Parameters ‘+(val1+val2+val3));

    }

  

</script>

</head>

<body>

  

    <form id=”form1″>

    <div style=”width:500px; height:400px; background-color:Gray;” >

    <input type=”button” onclick=”Add(5,6,7);” value=”Add with Three Parameters” />

    <input type=”button” onclick=”Add(5,6);” value=”Add with Two Parameters” />

    <input type=”button” onclick=”Add(5);” value=”Add with One Parameters” />

    <input type=”button” onclick=”Add();” value=”Add with No Parameters” />

    </div>

    </form>

</body>

</html>

 

What is the out put of the above code, when we click on the button with value ‘Add with No Parameters’ or any other button.?

 

If we expect the alert message 

 

  alert(‘Add With No Parameters ‘);

 

And if we say whenever we click on a button, its corresponding Add function will be called,we are  absolutely wrong.If you have any doubt run this code.

 

Whatevr the button we click,

 

 alert(‘Add With Three Parameters ‘+(val1+val2+val3));

 

 will be called irrespective of the javascrpt function signature.

 

Javascrit won’t suport function overloading.When we define a function with the same name but with different parameters,the function call directly goes to the function which is defined at the last. i.e. the last function in the order.

 

If we change the order of the functions,the function which is last in the definitions will be called.

 

Here whats happening is, the  function which is defined at the last will overwrite the previously defined functions.

Comments»

No comments yet — be the first.