Function that takes an object with optional/default properties as a parameter?

前端 未结 2 1849
天命终不由人
天命终不由人 2021-01-12 01:28

I understand that, using ES6 syntax, a function can be made that takes an object as a parameter and that parameter can have a default value, like so:

functio         


        
相关标签:
2条回答
  • 2021-01-12 01:50

    You can use destructuring in parameters to provide default values:

    function exampleFunction({val1 = 1, val2 = 2} = {}) {
      console.log(val1, val2);
    }
    exampleFunction({val1: 5});
    exampleFunction();

    If you want to keep the parameter as an object, you can use Object.assign:

    function exampleFunction(origParams = {}) {
      const objParam = Object.assign({ val1: 1, val2: 2 }, origParams);
      console.log(objParam.val1, objParam.val2);
    }
    exampleFunction({val1: 5});
    exampleFunction();

    0 讨论(0)
  • 2021-01-12 02:07

    Probably not as clean as you're looking for, but you can do this instead

    function exampleFunction(objParams) {
      const defParams = { val1: 1, val2: 2 };
    
      const finalParams = { ...defParams, ...objParams }
      // final params takes the default params and overwrites any common properties with incoming params
    
      // ...
    }
    
    0 讨论(0)
提交回复
热议问题