Function overloading in Javascript - Best practices

后端 未结 30 1481
难免孤独
难免孤独 2020-11-22 03:33

What is the best way(s) to fake function overloading in Javascript?

I know it is not possible to overload functions in Javascript as in other languages. If I neede

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:19

    #Forwarding Pattern => the best practice on JS overloading Forward to another function which name is built from the 3rd & 4th points :

    1. Using number of arguments
    2. Checking types of arguments
    window['foo_'+arguments.length+'_'+Array.from(arguments).map((arg)=>typeof arg).join('_')](...arguments)
    

    #Application on your case :

     function foo(...args){
              return window['foo_' + args.length+'_'+Array.from(args).map((arg)=>typeof arg).join('_')](...args);
    
      }
       //------Assuming that `x` , `y` and `z` are String when calling `foo` . 
      
      /**-- for :  foo(x)*/
      function foo_1_string(){
      }
      /**-- for : foo(x,y,z) ---*/
      function foo_3_string_string_string(){
          
      }
    

    #Other Complex Sample :

          function foo(...args){
              return window['foo_'+args.length+'_'+Array.from(args).map((arg)=>typeof arg).join('_')](...args);
           }
    
            /** one argument & this argument is string */
          function foo_1_string(){
    
          }
           //------------
           /** one argument & this argument is object */
          function foo_1_object(){
    
          }
          //----------
          /** two arguments & those arguments are both string */
          function foo_2_string_string(){
    
          }
           //--------
          /** Three arguments & those arguments are : id(number),name(string), callback(function) */
          function foo_3_number_string_function(){
                    let args=arguments;
                      new Person(args[0],args[1]).onReady(args[3]);
          }
         
           //--- And so on ....   
    

提交回复
热议问题