JavaScript › Design Patterns in JavaScript
How do you implement the Proxy pattern using JavaScript's built-in Proxy object?
AdvancedAnswer
JavaScript's native Proxy wraps a target object with traps (get, set, has, etc.) that intercept and can customize fundamental operations on it, letting you add validation, logging, or virtual properties transparently.
const validated = new Proxy({}, {
set(target, prop, value) {
if (prop === 'age' && value < 0) throw new Error('Invalid age');
target[prop] = value;
return true;
}
});
validated.age = -5; // throwsReal-world example Building a reactive state object (like Vue 3's reactivity system) that tracks property reads and writes.