How to implement the overloading of JS function

Source: Internet
Author: User

Tag: Ber alert call contains version span same else turn

The ECMAScript function does not implement overloading as it is in the traditional sense. In other languages, such as Java, you can write two definitions for a function, as long as the two defined signatures (the type and number of parameters that are accepted) are different. As mentioned earlier, the ECMASCIRPT function has no signature because its arguments are represented by an array containing 0 or more values. Without a function signature, the real overload is impossible.

If two functions with the same name are defined in ECMAScript, the name belongs only to the post-defined function. Take a look at the following example:

function addsomenumber (num) {    return num +;} function addsomenumber (num) {    return num +;} var //  -

Here, the function addsomenumber () is defined two times. The first version adds 100 to the parameter, while the second version adds 200 to the parameter. Since the function defined above is overwritten by the later functions, the returned result is 300 when the function is called in the last line of code.

As mentioned earlier, you can mimic the overloads of a method by examining the type and number of parameters in the incoming function and reacting differently.

function Addsomenumber (NUM1) {     var num1= arguments.length;      if (1 = = num1)        {var num2= arguments[1];        Alert ("High:" +num1+ ", Width:" +num2);      Else {        alert ("high =:" +NUM1);}     }

Personal understanding Shallow, welcome correction!

After the timely replenishment ~


How to implement the overloading of JS function

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: 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.