Function overloading in Javascript

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 needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way:

  • Using different names in the first place
  • Using optional arguments like y = y || 'default' y = y || 'default'
  • Using number of arguments
  • Checking types of arguments
  • Or how?

  • The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

    What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

    function foo(a, b, opts) {
    
    }
    
    
    foo(1, 2, {"method":"add"});
    foo(3, 4, {"test":"equals", "bar":"tree"});
    

    Then you can handle it anyway you want in your method. [Switch, if-else, etc.]


    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


    There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. You have to check inside the function how many arguments have been passed and what type they are.

    链接地址: http://www.djcxy.com/p/1496.html

    上一篇: 如何通过一个普通的JavaScript对象与作为成员的对象进行循环?

    下一篇: JavaScript中的函数重载