我想使用代理創建動態的不可配置屬性。我嘗試這樣做:使用代理創建動態的不可配置屬性
const proxy = new Proxy({}, {
getOwnPropertyDescriptor() {
return {
configurable: false,
enumerable: false,
};
},
});
console.log(Reflect.getOwnPropertyDescriptor(proxy, 'test'));
但我發現了一個錯誤:
TypeError: 'getOwnPropertyDescriptor' on proxy: trap reported non-configurability for property 'test' which is either non-existant or configurable in the proxy target
MDN說:
A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
但它並不能說明什麼這背後的推理。
有沒有解決此錯誤的方法?
很好的解釋,謝謝。你如何看待我的解決方案(發佈爲自己的答案)?是否有任何我沒有想到的副作用? –
@Gothdo是的,這應該正常工作。你可能會遇到像另一個代理或不可擴展對象那樣的更一般的目標,但如果你使用'{}'而不把它暴露給其他代碼,我沒有看到任何問題。 – Oriol