JavaScript only pretends to support function overloading
I frequently use method overloading a lot in my C# code to allow optional parameters, so when I wanted to implement a simple popup function with optional support for virtual root and website based on the url, here's what I came up with:
function showPopUp(virtual, url, height, width)
{
if(location.pathname.indexOf(virtual)>=0)
{
//we're running in the virtual root, so prepend it to the url
url=virtual+url;
}
showPopUp(url, height, width);
}
function showPopUp(url, height, width)
{
window.open(url, 'PopUpWindow', 'toolbar=no,directories=no,menubar=no,resizable=no,status=no,height=' + height + ',width=' + width);
}
{
if(location.pathname.indexOf(virtual)>=0)
{
//we're running in the virtual root, so prepend it to the url
url=virtual+url;
}
showPopUp(url, height, width);
}
function showPopUp(url, height, width)
{
window.open(url, 'PopUpWindow', 'toolbar=no,directories=no,menubar=no,resizable=no,status=no,height=' + height + ',width=' + width);
}
Javascript sneakily pretends to support this - no script error - every time I called the function, the virtual root wasn't being added on. That's because Javascript doesn't support method overloading; it just uses the function which was defined last (thanks, Bertrand, for verifying my hunch). I had to give the second function a different name, and it all worked.
Here's an easy way to verify - this will show the second message:
<html>
<head>
<script>
function test(one,two)
{
alert('expected: first function with two parameters');
}
function test(one)
{
alert('surprise! second function with one parameter');
}
</script>
</head>
<body onload="javascript:test('first','second')">
</body>
<head>
<script>
function test(one,two)
{
alert('expected: first function with two parameters');
}
function test(one)
{
alert('surprise! second function with one parameter');
}
</script>
</head>
<body onload="javascript:test('first','second')">
</body>