read-only proxy

JSobjectbuilt-inProxyexample ⟩ read-only proxy

uses Proxy to create a read-only wrapper for an object.

// 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.

Last updated