EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

How to test if an object is a Proxy? #82

Open EdwardZZZ opened 1 year ago

EdwardZZZ commented 1 year ago
// Node.js

import * as util from 'util';

util.types.isProxy();
// use Symbol
const obj = {
    a: {
        b: {
            c: {
                d: undefined,
            }
        }
    }
}

const isProxyKey = Symbol.for('is_proxy_key');

const proxyCfg = {
    set(target: typeof obj, p: keyof typeof obj, value: any, receiver: any) {
        console.log('set', target, p, value, receiver);
        return true;
    },
    get(target: typeof obj, p: keyof typeof obj, receiver: any) {
        const res = Reflect.get(target, p, receiver);

        if (typeof res === 'object' && !res[isProxyKey]) {
            Reflect.defineProperty(res, isProxyKey, {
                enumerable: false,
                value: true,
            });
            return new Proxy(res, proxyCfg);
        }

        return res;
    }
};

const newObj: any = new Proxy(obj, proxyCfg);

newObj.a.b.c.d = 234;
console.log(JSON.stringify(newObj, null, 4));