JavaScript does not have a function overload &arguments object

Source: Internet
Author: User

For people 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 run the results.

Alert (ON):

Alert (+/-):

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

There is no function overload in JavaScript, and the second one overrides the first when two identical function names are present. 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, according to his length to determine the number of parameters of the function ...

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaScript does not have function overloading &arguments objects

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.