Function overloading in Javascript - Best practices

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

    JavaScript is untyped language, and I only think that makes sense to overload a method/function with regards to the number of params. Hence, I would recommend to check if the parameter has been defined:

    myFunction = function(a, b, c) {
         if (b === undefined && c === undefined ){
              // do x...
         }
         else {
              // do y...
         }
    };
    

提交回复
热议问题