Handling optional parameters in javascript

前端 未结 12 910
无人共我
无人共我 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:04

    Are you saying you can have calls like these: getData(id, parameters); getData(id, callback)?

    In this case you can't obviously rely on position and you have to rely on analysing the type: getType() and then if necessary getTypeName()

    Check if the parameter in question is an array or a function.

    0 讨论(0)
  • 2020-11-28 20:10

    I recommend you to use ArgueJS.

    You can just type your function this way:

    function getData(){
      arguments = __({id: String, parameters: [Object], callback: [Function]})
    
      // and now access your arguments by arguments.id,
      //          arguments.parameters and arguments.callback
    }
    

    I considered by your examples that you want your id parameter to be a string, right? Now, getData is requiring a String id and is accepting the optionals Object parameters and Function callback. All the use cases you posted will work as expected.

    0 讨论(0)
  • 2020-11-28 20:11

    I think you want to use typeof() here:

    function f(id, parameters, callback) {
      console.log(typeof(parameters)+" "+typeof(callback));
    }
    
    f("hi", {"a":"boo"}, f); //prints "object function"
    f("hi", f, {"a":"boo"}); //prints "function object"
    
    0 讨论(0)
  • 2020-11-28 20:12

    So use the typeof operator to determine if the second parameter is an Array or function.

    This can give some suggestions: http://www.planetpdf.com/developer/article.asp?ContentID=testing_for_object_types_in_ja

    I am not certain if this is work or homework, so I don't want to give you the answer at the moment, but the typeof will help you determine it.

    0 讨论(0)
  • 2020-11-28 20:12

    You can use the arguments object property inside the function.

    0 讨论(0)
  • 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!");}
    });
    
    0 讨论(0)
提交回复
热议问题