Search code examples
javascriptdom-events

Unexpected call to a function in JavaScript


I'm not really good at JavaScript so I'm here asking.

Below is a sample code:

<html>
<head>
<script>
function test(one)
{
alert('surprise! first function with one parameter');
}

function test(one,two)
{
alert('expected: second function with two parameters');
}
</script>
</head>
<body onload="javascript:test('first')">
</body>
</html>

Questions:

I expected that that 'surprise! first function with one parameter' would be then alerted onload because I call the function with one parameter only. To my surprise it alerted in the second function.

  • Can someone explain this to me why?
  • and how can I make my way around it?

Solution

  • Javascript doesn't support method overloading; It just overwrites the function so the last one will get called every time.

    A way around it is just to make 1 function and put some conditions in there to check if the variables are set.