javascript - 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 }
解决方案
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);
推荐阅读
- node.js - 如何在node.js中使用multer和google drive api将多部分数据从表单上传到google drive?
- javascript - 在使用 JavaScript 填写表单之前,如何防止表单提交?
- python - 如何获得 cartopy 大地测量图的转换数据?
- ios - 需要从 URL 设置图像而不闪烁。阅读描述以了解完整的场景
- excel - 以编程方式打开连接到表格模型的 Excel 文档
- mysql - 在数据库中创建、更新、删除视图
- java - 水平 RecyclerView 中的上一个和下一个按钮
- c++ - 为模板类中的枚举类重载运算符<<
- neo4j - Neo4J本赛季出手次数最多和最少的球队
- php - 在 GitHub Actions 中使用 $_ENV 数组