Can we set persistent default parameters which remain set until explicitly changed?

后端 未结 4 1141
你的背包
你的背包 2020-12-02 00:37

The below is a function fn where expected result is for a, b, c to defined at every call of fn, whether an o

4条回答
  •  一个人的身影
    2020-12-02 01:23

    No

    The best that can be done is either your own answer or this:

    const fn = (default_parameters) => { 
      default_parameters = Object.assign({}, {a: 1, b: 2, c: 3},default_parameters);
      console.log('These are the parameters:');
      console.log(default_parameters);
    }
    
        fn();
    
        fn({b: 7});
    
        fn({g: 9, x: 10});

    The default parameter block is only executed if the value is not set, so your own answer is the best that is on offer ie use two parameters

    You can convince yourself of this by creating a code block that will fail if executed and testing that passing a parameter works (to show that the code block is not executed) and testing that not passing a parameter fails (showing that the code block is only executed when no parameter is passed).

    This should demonstrate clearly that any paramter passed will prevent the default parameter from being evaluated at all.

        const fn = (default_parameters = (default_parameters = Object.assign({}, {a: 1, b: 2, c: 3},default_parameters))) => { 
          
          console.log('These are the parameters:');
          console.log(default_parameters);
        }
    
            fn({b: 7});
            
            fn();
    
            fn({g: 9, x: 10});

提交回复
热议问题