...

View Full Version : overloading in JavaScript



piz
06-01-2003, 06:27 PM
Hi,

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

Thx.
piz

shlagish
06-01-2003, 07:11 PM
What's overload?

jkd
06-01-2003, 07:15 PM
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.

Garadon
06-01-2003, 07:33 PM
you could do a kind of fake overloading like this, it is far from ideal lol




<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>

nightwolfcem
05-21-2009, 10:00 AM
http://codingforums.com/showthread.php?t=166789



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum