Js cannot directly implement method overloading, but each function has a special parameter arguments, which can be used to implement method overloading, the specific example below shows that there is no way to directly implement method overloading in js, because if multiple methods with the same name but different number of parameters are defined in js, in fact, only the last method can be actually called, and other methods are overwritten.
However, each function has a special parameter, arguments, which can be used to implement method overloading.
For example:
The Code is as follows:
Function Add (firstnumber, sencondnumber ){
Return firstnumber + sencondnumber;
}
Only two parameters can be processed. If there are multiple parameters or no parameters, one parameter cannot be processed. If no parameter is passed, firstnumber and sencondnumber are all undefined. If a parameter is passed, it is equivalent to assigning only firstnumber values, and sencondnumber is still undefined. On the contrary, if more than two parameters are passed, it is equivalent to firstnumber and sencondnumber. Although there are other parameters, they are ignored during processing. If you can obtain other parameters, You can process them. In this case, you can think of the special parameter arguments of the function. This includes all the parameters passed to the function. You can use it to achieve method overloading.
The preceding method is modified as follows:
The Code is as follows:
Function Add (firstnumber, sencondnumber ){
If (arguments. length = 0) // No parameter is passed
{
Return null;
}
Else if (arguments. length = 1) {// a parameter is passed.
Return firstnumber; // return arguments [0];
}
Else if (arguments. length = 2) // two parameters are passed.
{
Return firstnumber + sencondnumber; // return arguments [0] + arguments [1];
}
Else {
Var total = 0;
For (var I = 0; I <arguments. length; I ++ ){
Total = total + arguments [I]
}
Return total;
}
}
Of course, the disadvantage of this method is that the order of parameters cannot be disrupted. If function implementation depends on the order of parameters, special processing must be performed, for example, null must be passed to occupy space.
Because the parameters passed to the function assign values to each parameter strictly in the order of defining the function, if you only want to assign values to the second parameter, you must pass two parameters, otherwise, the passed value is assigned to the first parameter, but not to the second parameter.
For example, if you only want to pass a value to sencondnumber but do not want to pass a value to firstnumber, you must call Add (null, 2) in this way (of course, the function must handle the situation where special values are passed ), if you call Add (2) in this way, you actually pass a value to firstnumber, which is equivalent to passing a parameter.