JS ⟩ object ⟩ built-in ⟩ Proxy ⟩ example ⟩ read-only proxy
uses Proxy to create a read-only wrapper for an object.
replit ⟩ read-only proxy
// make an object read-only function readOnly(o) { // throw error when trying to set/add/delete property. function throwError() { throw new TypeError(`proxy object is read-only.`); } // return proxy return new Proxy(o, { set : throwError, // can't set : proxy[key] defineProperty: throwError, // can't add : proxy[key] deleteProperty: throwError, // can't delete: proxy[key] setPrototypeOf: throwError, // can't set : proxy's prototype }); } let o = { x: 1, y: 2 }; // normal writable object let p = readOnly(o); // read-only version of it p.x, // 1 p.y, // 2 p.z, // undefined p.x = 2, // can't set p.x : ⛔ [TypeError] proxy object is read-only. delete p.y, // can't delete p.y: ⛔ [TypeError] proxy object is read-only. p.z = 3, // can't add p.z : ⛔ [TypeError] proxy object is read-only. p.__proto__ = {}, // can't set proto : ⛔ [TypeError] proxy object is read-only.
JS.info ⟩ Proxy and Reflect
JavaScript: The Definitive Guide ⟩
14.6 The Reflect API
14.7 Proxy Objects
Proxy
Reflect
Last updated 1 year ago