Function overloading in Javascript - Best practices

后端 未结 30 1519
难免孤独
难免孤独 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:16

    there is no actual overloading in JS, anyway we still can simulate method overloading in several ways:

    method #1: use object

    function test(x,options){
      if("a" in options)doSomething();
      else if("b" in options)doSomethingElse();
    }
    test("ok",{a:1});
    test("ok",{b:"string"});
    

    method #2: use rest (spread) parameters

    function test(x,...p){
     if(p[2])console.log("3 params passed"); //or if(typeof p[2]=="string")
    else if (p[1])console.log("2 params passed");
    else console.log("1 param passed");
    }
    

    method #3: use undefined

    function test(x, y, z){
     if(typeof(z)=="undefined")doSomething();
    }
    

    method #4: type checking

    function test(x){
     if(typeof(x)=="string")console.log("a string passed")
     else ...
    }
    

提交回复
热议问题