Javascript cannot support function overloading, as shown below:
CopyCode The Code is as follows: <script language = "JavaScript">
Function f (length)
{
Alert ("high:" + length );
}
Function f (length, width)
{
Alert ("height:" + Length + ", width:" + width );
}
</Srcipt>
The above Code does not actually work, because the number of parameters in the function definition has nothing to do with the number of parameters in the function call. F. arguments [0] and F. arguments [1] gets the first and second parameters passed in when calling, so defining function (length) and calling F (10, 10) is no problem. So in the above Code, the second function can never be called. How can we implement functions like function overloading?
In the function definition, F. Arguments. length is used to determine the number of parameters passed in during the call. Then, different processing methods are used for different situations.
As follows:Copy codeThe Code is as follows: <script language = "JavaScript">
Function f ()
{
VaR Len = arguments. length;
If (1 = Len)
{
VaR length = arguments [0];
VaR width = arguments [1];
F2 (length, width );
}
Else
{
VaR length = arguments [0];
F1 (length );
}
}
Function F1 (length)
{
Alert ("high:" + length );
}
Function F2 (length, width)
{
Alert ("height:" + Length + ", width:" + width );
}
</Srcipt>
in this way, you can input a parameter to function f () or two parameters, such as F (10) and F (10, 10).
in my opinion, in this way, the overload can be implemented, but it is not very easy to use. We can implement the overload in a function according to the actual situation. If the two functions to be reloaded have a large difference, we will keep the two functions, if the implementation of the two functions is almost the same, you can judge in a function and process different parts, instead of writing three functions as shown above: copy Code the code is as follows: