实现说明
整个示例围绕函数 expensive组织。
使用要点
- 直接运行文件,输出会带上标签,比如
after guards:、after tighten:、right side evaluated——输出的每一行都能指回产生它的那次调用。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 expensive。
主签名形如 function expensive()
核心语句
opts.host ??= 'localhost'; // '' 不是 nullish:保持原值
opts.port ||= 8080; // 0 是假值:被覆盖
opts.retries ||= 5; // 3 是真值:不动
opts.tags ??= []; // null 是 nullish:补默认
console.log('after guards:', JSON.stringify(opts));
cached.value ??= expensive();
empty.value ??= expensive();
代码示例
// ??= 只在 null/undefined 时写入;||= 只在假值时写入;&&= 只在真值时写入
const opts = { host: '', port: 0, retries: 3, tags: null };
opts.host ??= 'localhost'; // '' 不是 nullish:保持原值
opts.port ||= 8080; // 0 是假值:被覆盖
opts.retries ||= 5; // 3 是真值:不动
opts.tags ??= []; // null 是 nullish:补默认
console.log('after guards:', JSON.stringify(opts));
// &&= 反过来:字段为真值时才覆盖,适合"只在已设置时收紧"
const policy = { level: 'warn', locked: '' };
policy.level &&= 'error';
policy.locked &&= 'on';
console.log('after tighten:', JSON.stringify(policy));
// 赋值只发生在需要时:右边的表达式不会被求值
let evaluations = 0;
function expensive() {
evaluations += 1;
return 'computed';
}
const cached = { value: 'present' };
cached.value ??= expensive();
const empty = {};
empty.value ??= expensive();
console.log('right side evaluated', evaluations, 'time(s):', cached.value, empty.value);