JS function definition can specify the form parameter name, more or less we will think that JS can support at least the number of different methods overload, but unfortunately this is just a false impression, JS all the parameters are passed in arguments pass, this parameter is similar to the array, in the function call, All the arguments are stored in this data structure, and the formal arguments we specify when we define the function are actually defined as a quick way to access the data in this structure. That is to say JS all functions are supported infinite parameters, plus the data type is weak type, then JS function in addition to the name is really no way to distinguish?
There is always a way, we can use the special object arguments in JavaScript to simulate function overload. Use it to determine the number or type of incoming arguments to distinguish between overloads.
1. Based on the number of parameters overload
JS to judge the number of incoming parameters can be judged by arguments.length this attribute;
Copy Code code as follows:
<script type= "Text/javascript" >
function Add () {
if (arguments.length = = 1) {
Alert (Arguments[0] + 10);
}
else if (Arguments.length = 2) {
Alert (Arguments[0] + arguments[1]);
}
}
Function call
Add (10);
Add (10, 20);
</script>
2. Overload based on parameter type
3 ways to determine the type of a variable:
1. The variable type is judged by the TypeOf statement, and the TypeOf statement returns the string corresponding to the type.
2. Use instanceof statement to judge variable type, instanceof statement return True/false.
3. Use the constructor property to determine the variable type, which returns the constructor reference used to construct the variable.
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 |
Copy Code code as follows:
<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) {
or instead: if (Arguments[i] instanceof number)
or instead: if (typeof (Arguments[i]) = = "Number")
Sum + + arguments[i];
}
}
return sum;
}
Function call
Alert (Add (10));
Alert (Add (10,20));
</script>