← 中文资源

简体中文版本

getOwnPropertyDescriptors 完整保留访问器描述符

借助 Object.getOwnPropertyDescriptors 与 Object.defineProperties 复制对象,完整保留 getter、不可枚举属性与 Symbol 键。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

spread getter? false
exact getter?  true
exact hiddenId: cfg-7 | sym: v2
live getter calls: 12 13

实现说明

演示用的数据放在这几个模块级绑定中: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);