Handling optional parameters in javascript

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

    Er - that would imply that you are invoking your function with arguments which aren't in the proper order... which I would not recommend.

    I would recommend instead feeding an object to your function like so:

    function getData( props ) {
        props = props || {};
        props.params = props.params || {};
        props.id = props.id || 1;
        props.callback = props.callback || function(){};
        alert( props.callback )
    };
    
    getData( {
        id: 3,
        callback: function(){ alert('hi'); }
    } );
    

    Benefits:

    • you don't have to account for argument order
    • you don't have to do type checking
    • it's easier to define default values because no type checking is necessary
    • less headaches. imagine if you added a fourth argument, you'd have to update your type checking every single time, and what if the fourth or consecutive are also functions?

    Drawbacks:

    • time to refactor code

    If you have no choice, you could use a function to detect whether an object is indeed a function ( see last example ).

    Note: This is the proper way to detect a function:

    function isFunction(obj) {
        return Object.prototype.toString.call(obj) === "[object Function]";
    }
    
    isFunction( function(){} )
    

提交回复
热议问题