Hint
Intercept fundamental object operations (get, set, has, deleteProperty) with handler traps
A Proxy wraps an object and intercepts fundamental operations using "trap" handler methods.
const handler = {
get(target, prop, receiver) {
console.log(`Getting: ${prop}`);
return Reflect.get(target, prop, receiver); // β always use Reflect
},
set(target, prop, value, receiver) {
if (typeof value !== 'number') throw new TypeError('Numbers only');
return Reflect.set(target, prop, value, receiver);
},
has(target, prop) {
return prop in target; // intercepts 'in' operator
},
deleteProperty(target, prop) {
if (prop.startsWith('_')) throw new Error('Cannot delete private');
return Reflect.deleteProperty(target, prop);
}
};
const obj = new Proxy({}, handler);
obj.x = 42;
obj.x; // logs "Getting: x" β 42
'x' in obj; // calls has trap
obj.y = 'str'; // TypeError
// Real-world use cases:
// 1. Validation
// 2. Reactive state (Vue 3 uses Proxy for reactivity!)
// 3. Default property values
// 4. Logging / debugging
// 5. Negative array indexing
const arr = new Proxy([], {
get: (t, p) => t[p < 0 ? t.length + +p : p]
});
arr[-1]; // last element