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