Javascript does not have a function signature like other programming languages (what is a function signature? Simply put, it means that the function accepts the parameter type and number of parameters, and some people think that the return type should also be included. For more information about the concept, visit the Internet ).
Therefore, Javascript cannot implement the same method name as other languages, and the number of parameters varies... This type of overload, do not believe you can try:
Copy codeThe Code is as follows:
Function show (){
Alert ("1 ");
}
Function show (num1 ){
Alert (num1 );
}
Window. onload = function (){
Show ();
Show (2 );
}
In breakpoint debugging, the show method without parameters will not be executed, and it will be overwritten by the show (num1) method.
Can't "overload" be implemented in Javascript? The answer is yes, but it is another method. Yes, it uses arguments.
So what is arguments? In JS, it is a special attribute. It can obtain the parameter value through subscript index like an array (but it is not an array) and get the number of parameters through length:
Copy codeThe Code is as follows:
Function showParamsCount (){
Alert ("number of parameters:" + arguments. length); // output: number of parameters: 4
Alert ("parameter with subscript index 3:" + arguments [3]); // output: parameter with subscript index 3: Hello
}
Window. onload = function (){
ShowParamsCount ("Hello", 4,5, "Hello ");
}
One more thing to know is that the name parameters of functions in JS are not necessary. Therefore, to know how many parameters are passed during the call, you must obtain the parameters through arguments.
Below is a simple method overload:
Copy codeThe Code is as follows:
Function showMessage (){
If (arguments. length = 1 ){
Alert (arguments [0]);
} Else if (arguments. length = 2 ){
Alert (arguments [0] + "said:" + arguments [1]);
} Else {
Return false;
}
}
Window. onload = function (){
ShowMessage ("Hi! ");
ShowMessage ("Zhang San", "Hi your sister ");
}
In this way, JS Overloading is implemented.
When I read this book about js advanced programming, I found that the value of arguments is always synchronized with the value of the corresponding named parameter. I have never paid attention to this problem before.
Copy codeThe Code is as follows:
Function showMessage (name, msg ){
Arguments [1] = "I can change the msg value ";
Alert (name + "said:" + msg); // output: Zhang San said: I can change the msg value.
}
Window. onload = function (){
ShowMessage ("Zhang San", "Hi your sister ");
}
Okay, this is the basic knowledge about js "overloading ".