Function overloading in Javascript - Best practices

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

    There is no way to function overloading in javascript. So, I recommend like the following by typeof() method instead of multiple function to fake overloading.

    function multiTypeFunc(param)
    {
        if(typeof param == 'string') {
            alert("I got a string type parameter!!");
         }else if(typeof param == 'number') {
            alert("I got a number type parameter!!");
         }else if(typeof param == 'boolean') {
            alert("I got a boolean type parameter!!");
         }else if(typeof param == 'object') {
            alert("I got a object type parameter!!");
         }else{
            alert("error : the parameter is undefined or null!!");
         }
    }
    

    Good luck!

提交回复
热议问题