Proxy Pattern
Proxy Pattern
Section titled “Proxy Pattern”Introduction
Section titled “Introduction”The Proxy pattern provides a surrogate that controls access to another object. JavaScript has built-in Proxy for this.
Implementation
Section titled “Implementation”const user = { name: 'Alice', role: 'user' };
const protectedUser = new Proxy(user, { get(target, prop) { if (prop === 'password') { throw new Error('Access denied'); } return target[prop]; },
set(target, prop, value) { if (prop === 'role' && target.role === 'admin') { throw new Error('Cannot change admin role'); } target[prop] = value; return true; }});
console.log(protectedUser.name); // 'Alice'// protectedUser.password; // Error: Access denied
// Caching proxyfunction createCacheProxy(fn) { const cache = new Map(); return new Proxy(fn, { apply(target, thisArg, args) { const key = JSON.stringify(args); if (cache.has(key)) return cache.get(key); const result = target.apply(thisArg, args); cache.set(key, result); return result; } });}Summary
Section titled “Summary”- Controls access to target objects
- Built-in JavaScript
ProxyAPI - Use cases: validation, caching, logging, access control