JavaScript does not have function overloading & Arguments Object

Source: Internet
Author: User

For those of you who have learned Java. function overloading is not an unfamiliar concept, but is there a function overload in JavaScript ... And then we're going to test it.

<script type= "Text/javascript" >  //javascript there is no function overloading phenomenon  var add=function (A, b) {return a+b;} var add=function (a,b,c) {return a+b+c;}
<span style= "White-space:pre" ></span>alert, alert (Add (+));  </script>
This case is modeled after the syntax in Java to simulate function overloading. Let's do the results.

Alert (ON):

Alert (+/-):

Results comparison found that the result of the first execution is Nan, and the result of the second execution is normal.

There is no phenomenon of function overloading in JavaScript. When there are two identical function names at the same time, the second one will overwrite the first one. So Alet will find the second function, but it is the third parameter in the argument is empty, so the result is reported in Nan.

So how do we imitate the function overloading in Java? Here we introduce the arguments object ...

<script type= "Text/javascript" >  //javascript there is no function overloading var add=function () {if (arguments.length==2) {return ARGUMENTS[0]+ARGUMENTS[1];} else if (arguments.length==3) {return arguments[0]+arguments[1]+arguments[2];}} Alert (Add (1,2,4));  </script>
Functon must be empty function () {}

According to arguments is an array that can infer the number of parameters of a function based on his length.

JavaScript does not have function overloading &amp; Arguments Object

Related Article

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.