getOwnPropertyDescriptors Preserves Accessors
Clone getters, setters, symbol keys, and non-enumerable flags faithfully with Object.getOwnPropertyDescriptors and Object.defineProperties instead of spread.
Code
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
spread getter? false
exact getter? true
exact hiddenId: cfg-7 | sym: v2
live getter calls: 12 13Inside the implementation — getOwnPropertyDescriptors Preserves Accessors
Demo state sits in top-level bindings: tagSym, ticks, source, spreadCopy.
What to watch for
- The whole dependency story is the language version itself.
Putting it to use
Output lines are prefixed (spread getter?, exact getter?, exact hiddenId:), pairing console messages strictly against discrete code milestones.
Core lines
return this.base + ticks;
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `tagSym`, `ticks`, `source`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.