实现说明
演示用的数据放在这几个模块级绑定中:tagSym、ticks、source、spreadCopy。
使用要点
- 供应链审查没有可查的对象——文件不引入任何包。
- 直接运行文件,输出会带上标签,比如
spread getter?、exact getter?、exact hiddenId:——输出的每一行都能指回产生它的那次调用。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 文件的状态由几个模块级绑定持有:tagSym、ticks、source。
核心语句
return this.base + ticks;
代码示例
const tagSym = Symbol('version');
let ticks = 0;
const source = {
base: 10,
get nextTick() {
ticks++;
return this.base + ticks;
},
[tagSym]: 'v2',
};
Object.defineProperty(source, 'hiddenId', { value: 'cfg-7', enumerable: false });
// Object spread evaluates `nextTick` eagerly into a static data property and drops `hiddenId`
const spreadCopy = { ...source };
// Descriptor copy preserves the live getter, non-enumerable property, and symbol key
const exactCopy = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
console.log('spread getter?', Boolean(Object.getOwnPropertyDescriptor(spreadCopy, 'nextTick').get));
console.log('exact getter? ', Boolean(Object.getOwnPropertyDescriptor(exactCopy, 'nextTick').get));
console.log('exact hiddenId:', exactCopy.hiddenId, '| sym:', exactCopy[tagSym]);
console.log('live getter calls:', exactCopy.nextTick, exactCopy.nextTick);