Function overloading in Javascript - Best practices

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

    As of July 2017, the following has been the common technique. Note that we can also perform type checking within the function.

    function f(...rest){   // rest is an array
       console.log(rest.length);
       for (v of rest) if (typeof(v)=="number")console.log(v);
    }
    f(1,2,3);  // 3 1 2 3
    

提交回复
热议问题