views:

71

answers:

6

Hi, 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?
+7  A: 

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.

D4V360
okay. thank you very much!
Reigel
A: 

In javascript the parameters for a function aren't required. You'd want to check to see if the parameter is undefined before using it.

If used this before in order to implement getter/setter type functionality in javascript similar to below:

var _pageSize;

function pageSize(value) {
    if (value) {
       _pageSize = value;
    }
    else {
       return _pageSize;
    }
}

You can then use the pageSize method to both get and set the page size like below:

if (pageSize() < 15) {
    pageSize(15)
}
Brian Hasden
A: 

Ah, Javascript doesn't do polymorphism like that. It does have an arguments collection that you can look in and then do the right thing given the inputs..

stuff like:

function calcAverage() 
{ 
   var sum = 0 
   for(var i=0; i<arguments.length; i++) 
      sum = sum + arguments[i] 
   var average = sum/arguments.length 
   return average 
} 
document.write("Average = " + calcAverage(400, 600, 83)) 
Bill Bingham
+2  A: 

You declare twice the function test. The 2nd one overwrite the first definition.

Mic
+1 thank you for that..
Reigel
+1  A: 

In JavaScript overloaded functions are not allowed. so in this case the second function overrides the first one and therefore you always see this result.

A work around for this is to check the values of the parameters:

function test(one,two)
{
if(two)
alert('expected: second function with two parameters');
else
alert('surprise! first function with one parameter');
}

Mendy
A: 

When calling such function:

function test(one,two)

With only one parameter, the argument "two" will have special type: undefined. Any attempt to access the variable two will fail with "two is undefined" error, to avoid such error use the typeof command:

function test(one,two)
{
   if (typeof two == "undefined") {
      //give default value
      two = "default value here";
   }
   ...
}
Shadow Wizard