JS itself does not support overloading, because the method call is only related to the method name, regardless of the number and type of parameters, it is this feature, we can implement the overload in a simpler way.
We can use array arguments to get variables and then perform different operations based on Arguments.length.
Simple example:
function Getsum () {
This is the function that calculates the sum
var sum=0;
for (Var i=0;i<arguments.length;i++) {
Sum+=arguments[i];
}
return sum;
}
document.write (Getsum ());//0
document.write (Getsum (1));//1
document.write (Getsum (1,2));//3
document.write (Getsum (1,2,3));//6
document.write (Getsum (1,2,3,4));//10
JavaScript cannot support the overload of a function, as follows:
<script language= "JavaScript" >
function f (length)
{
Alert ("Gao is:" +length);
}
function f (length,width)
{
Alert ("High": "+length+", Wide for: "+width);"
}
</srcipt>
The above code doesn't work, because the number of arguments in the function definition has nothing to do with the number of arguments in the function call. You can get the first and second arguments passed in in a function with f.arguments[0] and f.arguments[1, so defining a function (length), followed by an F (10,10) call, is OK. So in the above code, the second function is never going to be invoked, so how do you implement functions like function overloading?
That is, in the function definition, use F.arguments.length to determine the number of arguments passed in at the call. Then different ways of dealing with different situations.
As follows:
<script language= "JavaScript" >
function f ()
{
var len= arguments.length;
if (1 = len)
{
var length = arguments[0];
var width = arguments[1];
F2 (length,width);
}
Else
{
var length = arguments[0];
F1 (length);
}
}
function f1 (length)
{
Alert ("Gao is:" +length);
}
function F2 (length,width)
{
Alert ("High": "+length+", Wide for: "+width);"
}
</srcipt>
In this way, you can pass a function f () to a parameter or pass in two parameters, such as f (10) and F (10,10);
Personally feel that, while this can be implemented overloading, but also not very good, we can according to the specific situation in a function to implement overloading, if you want to overload the two functions of a large difference, then retain two functions, and if the implementation of two functions is basically similar, then you can judge in a function, processing different parts, Instead of writing three functions like the one above, the following:
<script language= "JavaScript" >
function f (length)
{
var len= arguments.len Gth
if (1 = len)
{
var width = ARGUMENTS[1];
alert ("High": "+length+", Wide for: "+width);"
}
Else
{
alert ("High:" + length);
}
}
</srcipt>