Within the JavaScript method, there is an array of variables called arguments, which is read-only and all the actual argument variables passed in are
In the inside, through which we can check the incoming parameters for type checking to achieve the effect of overloading.
There are two ways to determine the type of a variable.
1, with the TypeOf statement:
Copy Code code as follows:
function Check () {
if (typeof arguments[0] = = ' string ')
Alert (' Your incoming argument is a string ');
else if (typeof arguments[0] = = ' number ')
Alert (' Your incoming argument is a number ');
}
2, with a property constructor with all JavaScript variables, this attribute points to the constructor used to construct the variable:
Copy Code code as follows:
function Check () {
if (Arguments[0].constructor = = String)
Alert (' Your incoming argument is a string ');
else if (arguments[0].constructor = number)
Alert (' Your incoming argument is a number ');
}
Table:
TypeOf Constructor
---------------------------
String string
Number number
Object Object
function function
Boolean Boolean
Object Array
Object User
Through this comparison table can be seen by the TypeOf can not accurately determine the specific type, so we use constructor to judge
Broken.
First we define a method to determine the type and number of parameters.
Copy Code code as follows:
function Checkargs (Types,args) {
Check the number of parameters
if (types.length!= args.length) {
return false;
}
Check parameter types
for (var i=0; i<args.length; i++) {
if (Args[i].constructor!= types[i]) {
return false;
}
}
return true;
}
We define a method to apply to the above method
Copy Code code as follows:
Function Show () {
Processing parameter is a call to a string
if (Checkargs ([string],arguments)) {
Alert (arguments[0]);
}
The processing parameter is a string and a number of calls
else if (Checkargs ([string,number],arguments)) {
var s = ';
for (var i=0; i<arguments[1]; i++) {
S+=arguments[0];
}
alert (s);
When the parameter does not meet the requirement, give a hint
}else{
Alert (' unsupported parameter ');
}
}
When we define a JavaScript method that is stricter on the parameter requirements, we can write the code in this way.