A proxy trap is a handler function that intercepts a particular operation on a JavaScript proxy. It can customize interactions such as reading or assigning properties, rather than controlling access to just one property as a getter or setter does. section 9.2
When an operation passes through a proxy, the engine runs the matching trap if the handler defines one; otherwise, the operation goes to the target object. Use Reflect.get and Reflect.set inside traps to pass property operations through while preserving the receiver as the value of this. section 9.2
Traps can intercept several kinds of operation, including:
- get and set for property reads and assignments. section 9.2
- deleteProperty for deletions, ownKeys for key-list operations, and defineProperty for property definition and assignment to a new property. section 9.2
Listing 9.3 A proxy with a getter and setter
const emperor = { name: "Komei" };
const representative = new Proxy(emperor, { #A
get: (target, key, receiver) => { #B
return key in target #B
? Reflect.get(target, key, receiver) #B
: "Don't bother the emperor!"; #B
}, #B
set: (target, key, value, receiver) => { #C
if (!(key in target)) { #C
console.warn("Setting this key is impermissible."); #C
return false; // Reject the operation #C
} #C
return Reflect.set(target, key, value, receiver); #C
}, #C
});
console.assert(
representative.name === "Komei",
"We can get the name property through a proxy",
);
representative.name = "Tenno";
console.assert(
emperor.name === "Tenno",
"We can set the name property through a proxy",
);
console.assert(
// @ts-expect-error -- The nickname property is not
[CA]part of the object's type
representative.nickname === "Don't bother the emperor!",
"The proxy guards against improper gets",
);
The proxy lets reads of existing properties and assignments through to the target, returns a custom message for missing properties, and rejects assignments to new properties. section 9.2

