function createLoggingProxy(target, name = "Object") { return new Proxy(target, { get(target, prop, receiver) { const value = Reflect.get(target, prop, receiver); console.log(`[${name}] GET ${String(prop)} → ${value}`); return typeof value === 'function' ? value.bind(target) // Preserve context for methods : value; }, set(target, prop, value, receiver) { console.log(`[${name}] SET ${String(prop)} = ${value}`); return Reflect.set(target, prop, value, receiver); } }); } const user = { name: "Alice", age: 30 }; const monitoredUser = createLoggingProxy(user, "User"); monitoredUser.age = 31; // Logs: [User] SET age = 31 console.log(monitoredUser.name); // Logs: [User] GET name → Alice
: It uses Reflect to capture the exact value, including getters that might compute results dynamically. 3. Validation Proxy (Top Security) A common requirement is to validate data before allowing mutations. This pattern powers libraries like Vuex and MobX. proxy made with reflect 4 top
// BAD get(target, prop) { return target[prop]; // Ignores proxy inheritance } // GOOD get(target, prop, receiver) { return Reflect.get(target, prop, receiver); // Maintains correct this } Sometimes you need a proxy made with reflect that can be revoked. Use Proxy.revocable . Validation Proxy (Top Security) A common requirement is