A Proxy wraps an object and routes fundamental operations through handler functions called traps. This turns ordinary reads, writes, deletions, and enumeration into interception points for validation, logging, and virtual properties. section 5.8
const originalDrawer = {
contents: 'tax documents',
isLocked: false
};Use the drawer object as the target that the Proxy will wrap. section 5.8
const dynamicDrawer = new Proxy(originalDrawer, {
get(target, property, receiver) {
console.log(`Accessing property: ${property}`);
if (property === 'securityLevel') {
return target.contents === 'classified'
? 'high' : 'normal';
}
return target[property];
},
set(target, property, value, receiver) {
console.log(`Setting ${property} = ${value}`);
if (property === 'contents' &&
typeof value !== 'string') {
throw new Error('Contents must be a string');
}
if (target[property] !== value) {
console.log(`Changed ${property} from ` +
`"${target[property]}" to "${value}"`);
}
target[property] = value;
return true;
}
});The handler logs access, computes a virtual securityLevel property, validates contents assignments, and records changes. section 5.8
A normal-looking interaction with intercepted behavior
Reading dynamicDrawer.contents invokes the get trap. Reading securityLevel computes a value that is not stored on the target. Assigning classified invokes the set trap, validates the string, and changes the target; the later securityLevel read reflects the new contents. section 5.8
Use Proxy when ordinary object features are insufficient:
- Intercept operations that getters and setters cannot cover, including missing-property access and removal. section 5.8
- Keep interaction syntax ordinary while applying custom validation, logging, or computed-property logic. section 5.8





