Preserve Getters With Property Descriptors
Copy objects with Object.getOwnPropertyDescriptors and defineProperties so getters stay live instead of being invoked once by spread.
Code
const account = {
owner: 'ada',
get balance() {
return 42;
},
};
// 展开运算符会“求值”getter,拷出来的是普通数字属性
const spread = { ...account };
const spreadDesc = Object.getOwnPropertyDescriptor(spread, 'balance');
console.log('spread balance:', spread.balance, 'still a getter?', spreadDesc.get !== undefined);
// getOwnPropertyDescriptors 保留访问器,defineProperties 原样挂回
const cloned = Object.defineProperties({}, Object.getOwnPropertyDescriptors(account));
const cloneDesc = Object.getOwnPropertyDescriptor(cloned, 'balance');
console.log('clone balance:', cloned.balance, 'still a getter?', cloneDesc.get !== undefined);What the code does
Module-level bindings hold the data — account, spread, spreadDesc, cloned — with no function scope in between.
Applying it
The demo output is labeled (spread balance:, clone balance:), so every printed line maps back to its originating operation.
Statements that matter
const cloned = Object.defineProperties({}, Object.getOwnPropertyDescriptors(account));
const spreadDesc = Object.getOwnPropertyDescriptor(spread, 'balance');
const cloneDesc = Object.getOwnPropertyDescriptor(cloned, 'balance');
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `account`, `spread`, `spreadDesc`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.