In many object-oriented high-level languages, there are overloads of methods. JavaScript does not have the concept of method overloading. But we can disguise this as a function overload by arguments this parameter.
Let's take a look at the code before the simulation:
Functions function Fun () { alert ("Sample Code") with no declarative parameters on the surface; } Fun ("xiaoming", +, true);//wrote three actual parameters
As a result we see that even when we declare a function without defining a formal parameter, we can write the actual parameters when invoking the method. (actually formal parameters are written to the programmer when they call the function)
Can we get the actual parameters in the code? The answer is yes: Please look at the code:
function Fun () {alert (arguments[0]) with no declaration form parameters on the surface ;//Gets the value of the first actual argument. alert (arguments[1]);//Gets the value of the second actual parameter. alert (arguments[2]);//Gets the value of the third actual parameter. alert (arguments.length);//Get the number of actual parameters. Alert ("Sample Code"); } Fun ("xiaoming", +, true);//wrote three actual parameters
Through the code we can know that the arguments (intrinsic property) itself is an array, its function is to store the actual parameters of the method.
With the above knowledge points, the simulation method overload will have the idea. We can use the number of actual parameters to make a judgment, thus executing different logic code. The simple code is as follows:
function Fun () { if (arguments.length = = 0) { alert ("Executes code without actual parameters"); } else if (arguments.length==1) { alert ("Executes code that passes in an actual parameter"); } else if (arguments.length==2) { alert ("Executes code that passes in two actual arguments"); } } Fun (); Fun ("Xiao Ming"); Fun ("Xiao Ming", "Floret");
Method overloading in JavaScript