How to Implement JS function Overloading

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.