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 & Arguments Object