In many object-oriented high-level languages, there is overloading of methods. And JavaScript does not have the concept of method overloading. But we can use the arguments parameter to disguise the function's overload
Before the simulation, let's look at the code:
The code copy is as follows:
//There is no function that declares formal parameters on the surface
function fun() {
alert("Sample Code");
}
fun("Xiao Ming", 100, true);//I wrote three actual parameters myself
Through the results, we see that even if we do not define formal parameters when declaring a function, we can write actual parameters when calling the method. (In fact, formal parameters are read when writing to programmers to call functions)
Can we get the actual parameters in the code? The answer is yes: Please see the code:
The code copy is as follows:
//There is no function that declares formal parameters on the surface
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("Xiao Ming", 100, true);//I wrote three actual parameters myself
Through the code, we can know that arguments (internal properties) are themselves an array, and their function is to store the actual parameters of the method.
With the above knowledge points, there will be ideas for reloading the simulation method. We can make a judgment based on the number of actual parameters, so as to execute different logical codes. The simple code is as follows:
The code copy is as follows:
function fun() {
if (arguments.length == 0) {
alert("Execute code without actual parameters");
}
else if(arguments.length==1)
{
alert("Execute the 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", "Xiao Hua");