In the JavaScript method, an array of variables called arguments is read-only.
Put it inside, through which we can check the type of input parameters to achieve the effect of overloading.
There are two methods to determine the type of a variable.
1. Use the typeof statement:
Copy codeThe Code is as follows:
Function check (){
If (typeof arguments [0] = 'string ')
Alert ('the parameter you passed in is a string ');
Else if (typeof arguments [0] = 'number ')
Alert ('the parameter you passed in is a number ');
}
2. Use a constructor attribute that is contained in all JavaScript variables. This attribute points to the constructor used to construct the variable:
Copy codeThe Code is as follows:
Function check (){
If (arguments [0]. constructor = String)
Alert ('the parameter you passed in is a string ');
Else if (arguments [0]. constructor = Number)
Alert ('the parameter you passed in is a number ');
}
Table:
Typeof constructor
---------------------------
String String
Number Number
Object
Function
Boolean Boolean
Object Array
Object User
Through this table, we can see that typeof cannot accurately determine the specific type, so we use constructor to judge
Disconnected.
First, we define a method to determine the parameter type and number.
Copy codeThe Code is as follows:
Function checkArgs (types, args ){
// Check the number of parameters
If (types. length! = Args. length ){
Return false;
}
// Check the parameter type
For (var I = 0; I <args. length; I ++ ){
If (args [I]. constructor! = Types [I]) {
Return false;
}
}
Return true;
}
We define a method to apply the above method.
Copy codeThe Code is as follows:
Function show (){
// The processing parameter is a string call
If (checkArgs ([String], arguments )){
Alert (arguments [0]);
}
// The processing parameter is a string and a number call
Else if (checkArgs ([String, Number], arguments )){
Var s = '';
For (var I = 0; I <arguments [1]; I ++ ){
S + = arguments [0];
}
Alert (s );
// Prompt when the parameter does not meet the requirements
} Else {
Alert ('unsupported parameters ');
}
}
When the JavaScript method we define has strict parameter requirements, you can use this method to write code.