Function overloading in Javascript - Best practices

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

    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) {
      // ...
      if (opts['test']) { } //if test param exists, do something.. 
    }
    
    
    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.]

提交回复
热议问题