JS function definition can specify the formal parameter name, more or less we will think that JS can at least support a different number of method overloads, but unfortunately this is only an illusion, JS all the parameters are passed in arguments, this parameter is similar to the array, in the function call, All of the arguments are stored in this data structure, and the formal parameters we specify when we define the function are actually a quick way to access the data inside the structure. That is, JS all the functions are supporting an infinite number of parameters, and the data type is weak type, then JS function in addition to the name is really no method difference?
There's always a way, we can use the special object arguments in JavaScript to simulate function overloading. Use it to determine the number or type of arguments passed in to differentiate overloads.
1. Overloading according to the number of parameters
JS judge the number of incoming parameters can be judged by arguments.length this attribute;
12345678910111213 |
<script type=
"text/javascript"
>
function add() {
if (arguments.length == 1) {
alert(arguments[0] + 10);
}
else if (arguments.length == 2) {
alert(arguments[0] + arguments[1]);
}
}
//函数调用
add(10);
add(10, 20);
</script>
|
2. Overloading by parameter type
3 ways to determine the type of variable:
1. Use the typeof statement to determine the variable type, and the TypeOf statement returns the string corresponding to the type.
2. Using the INSTANCEOF statement to determine the variable type, the instanceof statement returns TRUE/FALSE.
3. Use the constructor property to determine the variable type, which returns the constructor reference used to construct the variable.
Comparison table: can be seen with typeof not accurate to determine the specific type, so we use constructor to judge.
typeof |
String |
Number |
Object |
function |
Boolean |
Object |
Object |
Constructor |
String |
Number |
Object |
Function |
Boolean |
Array |
User Define |
123456789101112131415161718 |
<script type=
"text/javascript"
>
function add()
{
if (arguments.length == 0)
return 0;
var sum=0;
for
(
var i=0; i<arguments.length; i++){
if
(arguments[i].constructor == Number){
//或者改为:if(arguments[i] instanceof Number)
//或者改为:if(typeof(arguments[i])=="number")
sum += arguments[i];
}
}
return sum;
}
//函数调用
alert(add(10));
alert(add(10,20));
</script>
|
JS function Overloading Solution