实现说明
defaults、envLayer、userLayer、merged 定义在模块顶层,中间不经过函数作用域。
一个对象字面量承载 retries、timeout、label——每个值都就地写死。
使用要点
- 演示输出是带标签的(
label present but undefined:、defaults intact:),每个操作都会留下自己的一行标注。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 跨调用保留的状态放在这些顶层绑定里:defaults、envLayer、userLayer。
核心语句
const withBlank = Object.assign({}, defaults, { label: undefined });
const envLayer = null; // e.g. no CLI overrides found for this run
const userLayer = { retries: 5, label: 'sync-job' };
const merged = Object.assign({}, defaults, envLayer, userLayer);
代码示例
const defaults = { retries: 2, timeout: 5000, label: 'job' };
// null and undefined sources are skipped; real layers overwrite key by key.
const envLayer = null; // e.g. no CLI overrides found for this run
const userLayer = { retries: 5, label: 'sync-job' };
const merged = Object.assign({}, defaults, envLayer, userLayer);
console.log(JSON.stringify(merged));
// Assigning undefined explicitly still overwrites: defaults do not "win".
const withBlank = Object.assign({}, defaults, { label: undefined });
console.log('label present but undefined:', withBlank.label);
// The first argument is mutated in place; pass {} to keep defaults untouched.
console.log('defaults intact:', JSON.stringify(defaults));