Search code examples
javascriptfunctionvalidationparametersparameter-object

javascript function parameter object verification


I want to make all my functions take a single object param so I can pass it a list of named arguments independent of order.

for example:

function A(param){

    this.first = param.first ? param.first : null;
    this.second = param.second ? param.second : null;

}

So I can make an A object by passing in anything and if the object doesn't have a first or second property then the object still gets made with all of its properties set to null or some other default value.

If I want to make a default A object I would like to just call new A() without any parameter object at all but then that throws an error because I'am trying to illegally access a property of 'undefined' so the constructor doesn't make anything.

I could make it like this:

function A(param){

    if(typeof param ==== 'undefined')param = {};
    this.first = param.first ? param.first : null;
    this.second = param.second ? param.second : null; 

}

But if I want to make all my functions take a single param object I will need to include this line in every function definition.

Is there a better way of achieving this result or is there away of manipulating the Function prototype such that all functions automatically get this check to make sure the param is there or is at least initialised so the code doesn't fall over when trying to access properties of 'undefined'.

Thanks.


Solution

  • You can use the || operator:

    function A(param){
      param == param || {};
      this.first = param.first || null;
      this.second = param.second || null; 
    }