Function overloading in Javascript - Best practices

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

    I often do this:

    C#:

    public string CatStrings(string p1)                  {return p1;}
    public string CatStrings(string p1, int p2)          {return p1+p2.ToString();}
    public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}
    
    CatStrings("one");        // result = one
    CatStrings("one",2);      // result = one2
    CatStrings("one",2,true); // result = one2true
    

    JavaScript Equivalent:

    function CatStrings(p1, p2, p3)
    {
      var s = p1;
      if(typeof p2 !== "undefined") {s += p2;}
      if(typeof p3 !== "undefined") {s += p3;}
      return s;
    };
    
    CatStrings("one");        // result = one
    CatStrings("one",2);      // result = one2
    CatStrings("one",2,true); // result = one2true
    

    This particular example is actually more elegant in javascript than C#. Parameters which are not specified are 'undefined' in javascript, which evaluates to false in an if statement. However, the function definition does not convey the information that p2 and p3 are optional. If you need a lot of overloading, jQuery has decided to use an object as the parameter, for example, jQuery.ajax(options). I agree with them that this is the most powerful and clearly documentable approach to overloading, but I rarely need more than one or two quick optional parameters.

    EDIT: changed IF test per Ian's suggestion

提交回复
热议问题