Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    piz
    piz is offline
    Regular Coder
    Join Date
    Jul 2002
    Location
    Barcelona
    Posts
    246
    Thanks
    0
    Thanked 0 Times in 0 Posts

    overloading in JavaScript

    Hi,

    There is no way to overload JavaScript Functions, isn't there?

    Thx.
    piz

  • #2
    Senior Coder
    Join Date
    Apr 2003
    Location
    Canada
    Posts
    1,063
    Thanks
    2
    Thanked 0 Times in 0 Posts
    What's overload?
    Shawn

  • #3
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    You can't. Javascript is loosely typed, so you can't distinguish function signatures based on datatypes of the arguments.

    i.e:

    int bla(int a, int b)
    int bla(double a, double b)

    in C++ can both be represented by

    function bla(a, b)

    in Javascript. As for differing amounts of arguments, Javascript really doesn't care about that either.

    function bla(a, b, c)
    is pretty much the same as
    function bla()
    except that in the former, a = arguments[0], b = arguments[1], c = arguments[2] in the namespace of the function.

  • #4
    Regular Coder
    Join Date
    Jul 2002
    Posts
    698
    Thanks
    0
    Thanked 0 Times in 0 Posts
    you could do a kind of fake overloading like this, it is far from ideal lol

    Code:
     
    
    <html>
    <head>
    <script language="JavaScript1.2">
    function dispatcher()
    {
      switch(arguments.length)
    	{
    	case 1:real1(arguments[0]);break;
      case 2:real2(arguments[0],arguments[1]);break;
    	case 3:real3(arguments[0],arguments[1],arguments[2]);break;
    	}
    }
    
    function real3(a,b,c)
    {
      alert(a+'-'+b+'-'+c);
    }
    
    function real2(a,b)
    {
      alert(a+'-'+b);
    	
    }
    
    function real1(a)
    {
      alert(a);
    }
    
    </script>
    </head>
    <body>
    <button  onClick="dispatcher('a','b')">Test</button>
    <button  onClick="dispatcher('a')">Test</button>
    <button  onClick="dispatcher('a','b','c')">Test</button>
    </body>
    </html>

  • #5
    New Coder
    Join Date
    Oct 2008
    Location
    Turkey
    Posts
    15
    Thanks
    0
    Thanked 1 Time in 1 Post


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •