Javascript disguises method overloading with arguments arguments

  • 2020-03-30 04:02:09
  • OfStack

In many high-level object-oriented languages, methods are overloaded. Javascript has no concept of method overloading. But we can disguise this as an overload of the function with arguments

Let's take a look at the code before we simulate it:


//Function
with no formal arguments declared on the surface function fun() {
alert(" The sample code ");
}
fun(" Xiao Ming ", 100, true);//I wrote three actual parameters

As a result, we see that even if we declare a function without defining formal arguments, we can write the actual arguments when calling a method. (formal arguments are actually written for programmers to see when they call functions.)

Can we get the actual parameters in the code? The answer is yes: look at the code:


//Function
with no formal arguments declared on the surface function fun() {
alert(arguments[0]);//Get the value of the first actual parameter. < br / > alert(arguments[1]);//Gets the value of the second actual parameter. < br / > alert(arguments[2]);//Get the value of the third actual parameter. < br / > alert(arguments.length);//You get the number of actual parameters. < br / > alert(" The sample code ");
}
fun(" Xiao Ming ", 100, true);//I wrote three actual parameters

The code tells us that arguments(the internal property) is itself an array that stores the actual arguments to the method.

After having the above knowledge, the simulation method overload has the train of thought. We can make a judgment based on the number of actual parameters to execute different logical code. The simple code is as follows:


function fun() {
if (arguments.length == 0) {
alert(" Execute code without actual parameters ");
}
else if(arguments.length==1)
{
alert(" Executes the code that passes in an actual parameter ");
}
else if(arguments.length==2)
{
alert(" Execute the code that passes in the two actual parameters ");
}
}
fun();
fun(" Xiao Ming ");
fun(" Xiao Ming ", " The little flower ");


Related articles: