Function overloading in Javascript - Best practices

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

    I just tried this, maybe it suits your needs. Depending on the number of the arguments, you can access a different function. You initialize it the first time you call it. And the function map is hidden in the closure.

    TEST = {};
    
    TEST.multiFn = function(){
        // function map for our overloads
        var fnMap = {};
    
        fnMap[0] = function(){
            console.log("nothing here");
            return this;    //    support chaining
        }
    
        fnMap[1] = function(arg1){
            //    CODE here...
            console.log("1 arg: "+arg1);
            return this;
        };
    
        fnMap[2] = function(arg1, arg2){
            //    CODE here...
            console.log("2 args: "+arg1+", "+arg2);
            return this;
        };
    
        fnMap[3] = function(arg1,arg2,arg3){
            //    CODE here...
            console.log("3 args: "+arg1+", "+arg2+", "+arg3);
            return this;
        };
    
        console.log("multiFn is now initialized");
    
        //    redefine the function using the fnMap in the closure
        this.multiFn = function(){
            fnMap[arguments.length].apply(this, arguments);
            return this;
        };
    
        //    call the function since this code will only run once
        this.multiFn.apply(this, arguments);
    
        return this;    
    };
    

    Test it.

    TEST.multiFn("0")
        .multiFn()
        .multiFn("0","1","2");
    

提交回复
热议问题