In many high-level object-oriented languages, there are overloads of methods. JavaScript has no way to overload this concept. But we can disguise this as a function overload by arguments this parameter
Before the simulation, let's look at the code:
The
code is as follows:
//There is no function on the surface to declare formal arguments
function Fun () {
Alert ("Sample Code");
}
Fun ("Xiaoming", true);/write yourself three actual parameters
Through the results we see that even when we declare a function without defining formal parameters, we can write the actual arguments when we invoke the method. (In fact, formal arguments are written to programmers when calling functions)
Can we get the actual parameters in the code? The answer is yes: Please look at the code:
The
code is as follows:
//There is no function on the surface to declare formal arguments
function Fun () {
alert (arguments[0]);//Get the value of the first actual parameter.
alert (arguments[1]);//Get the value of the second actual parameter.
alert (arguments[2]);//Get the value of the third actual parameter.
alert (arguments.length);//Get the number of actual parameters.
Alert ("Sample Code");
}
Fun ("Xiaoming", true);/write yourself three actual parameters
Through the code we can know that the arguments (internal property) itself is an array, and its function is to store the actual parameters of the method.
After the above knowledge point, the simulation method overload has the idea. We can use the number of actual parameters to make a judgment, thus executing different logical code. The simple code is as follows:
The code is as follows:
function Fun () {
if (arguments.length = = 0) {
alert ("Execute code with no actual parameters");
}
else if (arguments.length==1)
{
alert ("Execute code passing in an actual parameter");
}
else if (arguments.length==2)
{
alert ("Execute code passing in two actual parameters");
}
}
Fun ();
Fun ("Xiao Ming");
Fun ("Xiao Ming", "Floret");