Function overloading in Javascript - Best practices

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

    If I needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way?

    The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.

    One of the way I think is suitable for most of the case is follows -

    Lets say you have method

    function foo(x)
    {
    } 
    

    Instead of overloading method which is not possible in javascript you can define a new method

    fooNew(x,y,z)
    {
    }
    

    and then modify the 1st function as follows -

    function foo(arguments)
    {
      if(arguments.length==2)
      {
         return fooNew(arguments[0],  arguments[1]);
      }
    } 
    

    If you have many such overloaded methods consider using switch than just if-else statements.

提交回复
热议问题