Function overloading in Javascript - Best practices

后端 未结 30 1530
难免孤独
难免孤独 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 03:54

    Another way to approach this is by using the special variable: arguments, this is an implementation:

    function sum() {
        var x = 0;
        for (var i = 0; i < arguments.length; ++i) {
            x += arguments[i];
        }
        return x;
    }
    

    so you can modify this code to:

    function sum(){
        var s = 0;
        if (typeof arguments[0] !== "undefined") s += arguments[0];
    .
    .
    .
        return s;
    }
    

提交回复
热议问题