Handling optional parameters in javascript

前端 未结 12 908
无人共我
无人共我 2020-11-28 19:19

I have a static javascript function that can take 1, 2 or 3 parameters:

function getData(id, parameters, callback) //parameters (associative array) and callb         


        
12条回答
  •  醉梦人生
    2020-11-28 20:13

    If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
    use this approach. The idea is simple - use literal objects to combine your parameters:

    function getData(id, opt){
        var data = voodooMagic(id, opt.parameters);
        if (opt.callback!=undefined)
          opt.callback.call(data);
        return data;         
    }
    
    getData(5, {parameters: "1,2,3", callback: 
        function(){for (i=0;i<=1;i--)alert("FAIL!");}
    });
    

提交回复
热议问题