首页 > 解决方案 > Default function parameters doesn't work as I expected

问题描述

I have this function:

const func = (a, b, options = { opt1: false, opt2: false, opt3: false }) => {
 // do something
 console.log(options); // { opt1: false, opt2: false, opt3: false }
}

so when I call it without any params, I'm getting this

func('a', 'b', { opt3: true });
// { opt3: true }

instead of expected:

// { opt1: false, opt2: false, opt3: true }

标签: javascriptnode.jsfunctionparameters

解决方案


You've defaulted options, but you haven't defaulted the various properties within options. Since you're supplying an object for options, that object is being used.

You could use destructuring to supply defaults for the properties, and then supply a blank default for the parameter:

const func = (a, b, { opt1 = false, opt2 = false, opt3 = false } = {}) => {
 // do something
 console.log(opt1, opt2, opt3);
};

func(1, 2, {opt1: true});
func(1, 2);

Of course, you end up with the options as discrete variables rather than as an object. You can always reconstitute the object:

const func = (a, b, { opt1 = false, opt2 = false, opt3 = false } = {}) => {
 const options = {opt1, opt2, opt3};
 // do something
 console.log(options);
};

func(1, 2, {opt1: true});
func(1, 2);

And of course, since that's your own object, you can happily assign other properties to it if you like without worrying about modifying the caller's object.

If you don't want to use destructuring, you just supply the defaults separately like we used to before ES2015, but perhaps with property spread rather than Object.assign:

const func = (a, b, options = {}) => {
 // do something
 options = {opt1: false, opt2: false, opt3: false, ...options };
 console.log(options);
};

func(1, 2, {opt1: true});
func(1, 2);


推荐阅读