identity (proxy)

JSobjectbuilt-inProxyexample ⟩ identity (proxy)

an (proxy) object that appears to have an infinite number of read-only properties, where each property value is its key, that is, identity[key] === key.

// identity (Proxy)
let identity = new Proxy({}, {

    // ------------------------------------
    // handler methods, triggered when ...
    // ------------------------------------
    
    // accessing `identity[key]`
    get(o, key, receiver) { return key; },    // identity[key] === key
    
    // testing if `key in identity`
    has(o, key) { return true; },             // always true
    
    // iterating through own keys of `identity`
    ownKeys(o) { 
        throw new RangeError("Infinite number of properties"); 
    },
    
    // accessing property descriptor of `identity[key]`
    getOwnPropertyDescriptor(o, key) {
        return {
            value: key,
            enumerable: false,    // non-writable/non-configurable/non-enumerable
            writable: false,
            configurable: false
        };
    },
    
    // setting `identity[key]`
    set(o, key, value, receiver) { return false },  // cannot set
    
    // deleting `identity[key]`
    deleteProperty(o, key) { return false },        // cannot delete
    
    // (re)defining properties of `identity`
    defineProperty(o, key, desc) { return false },  // cannot (re)define
    
    // testing if `identity` is extensible
    isExtensible(o) { return false },               // always false
    
    // getting prototype of `identity`
    getPrototypeOf(o) { return null },              // no prototype
    
    // setting prototype of `identity`
    setPrototypeOf(o, proto) { return false },      // cannot set
});

// test identity
identity.x,            // 'x'
identity.toString,     // 'toString'
identity[0],           // '0'

delete identity.x,        // ⛔ [TypeError] 'deleteProperty' on proxy: trap returned falsish for property 'x'
identity.x = 1,           // ⛔ [TypeError] 'set' on proxy: trap returned falsish for property 'x'
Object.keys(identity),    // ⛔ [RangeError] Infinite number of properties
for (let p of identity);, // ⛔ [TypeError] identity is not iterable

Last updated