Function overloading in Javascript - Best practices

后端 未结 30 1527
难免孤独
难免孤独 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条回答
  •  -上瘾入骨i
    2020-11-22 03:54

    For your use case, this is how I would tackle it with ES6 (since it's already the end of 2017):

    const foo = (x, y, z) => {
      if (y && z) {
        // Do your foo(x, y, z); functionality
        return output;
      }
      // Do your foo(x); functionality
      return output;
    }
    

    You can obviously adapt this to work with any amount of parameters and just change your conditional statements accordingly.

提交回复
热议问题