In many high-level object-oriented languages, there are method overloading. And javascript has no concept of method overloading. But we can use the arguments parameter to disguise it as an overload of the function
Let’s take a look at the code before simulating:
//Functions that do not declare formal parameters on the surface
function fun() {
alert("Sample code");
}
fun("Xiao Ming", 100, true);//I wrote three actual parameters
From the results, we see that even if we do not define formal parameters when declaring the function, we can still write actual parameters when calling the method. (Actually, formal parameters are written for programmers to see when calling functions)
Can we get the actual parameters in the code? The answer is yes: please see the code:
//Functions that do not declare 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 actual number of parameters.
alert("Sample code");
}
fun("Xiao Ming", 100, true);//I wrote three actual parameters
Through the code, we can know that arguments (internal properties) itself is an array, and its function is to store the actual parameters of the method.
With the above knowledge points, you will have ideas for overloading simulation methods. We can make a judgment based on the number of actual parameters to execute different logic codes. The simple code is as follows:
function fun() {
if (arguments.length == 0) {
alert("Execute code without actual parameters");
}
else if(arguments.length==1)
{
alert("Execute the code passed in an actual parameter");
}
else if(arguments.length==2)
{
alert("Execute the code passed in two actual parameters");
}
}
fun();
fun("Xiao Ming");
fun("Xiao Ming", "Xiao Hua");
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn