Javascript basic function overloading is described in detail

  • 2020-03-26 21:37:34
  • OfStack

Javascript does not have a function signature like other programming languages (what is a function signature, simply means the type and number of arguments a function accepts, and some people think the return type should also be included. Specific concept everybody can inquire on the net).

So Javascript is not like other languages to implement the same method name, the number of parameters are different... This kind of overloaded, do not believe you can try:


         function show(){
             alert("1");
         }
         function show(num1){
             alert(num1);
         }

         window.onload=function(){
             show();
             show(2);
         }

Under breakpoint debugging, the show method with no parameters will not be executed, it will be overwritten by the show(num1) method.

So Javascript can't be "overloaded"? The answer is yes, just another way. Yes, using arguments.

So what are arguments? In JS, it is a special property, which can get the value of the parameter by subscript index like an array (but it is not an array), and the number of parameters by length:


         function showParamsCount(){
             alert(" Number of parameters :"+arguments.length);//Output: number of parameters :4
             alert(" The index is 3 The parameters of the :"+arguments[3]);//Output: parameter with index of 3: hello
         }

         window.onload=function(){
             showParamsCount("Hello",4,5," hello ");
         }

Also know that named arguments to functions in JS are not required, so you still have to get arguments through arguments to know how many arguments are passed when the call is made.

Here's a simple method overload:


         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 younger sister ");
         }

In this way, JS overloading is implemented.

While reading js advanced programming, I found that the value of arguments is always synchronized with the value of the corresponding named parameter. I have not noticed this problem before


         function showMessage(name,msg){
             arguments[1]=" I can change msg The value of the ";
             alert(name+" said :"+msg);//Output: zhang SAN said: I can change the value of MSG
         }

         window.onload=function(){
             showMessage(" Zhang SAN ","Hi  Your younger sister ");
         }

Okay, so much for the basics of js overloading


Related articles: