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');
}
</s开发者_开发技巧cript>
</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?
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.
You declare twice the function test. The 2nd one overwrite the first definition.
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');
}
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)
}
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))
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";
}
...
}
精彩评论