A Proxy is an intermediary for an object: interactions with the proxy can trigger custom behavior before they reach the target. Unlike getters and setters, which control individual properties, proxy traps can handle many kinds of object operations. section 9.2
A proxy is created with a target and a handler object:
- The handler’s traps intercept operations such as reading or assigning properties. If no trap handles an operation, it passes through to the target. section 9.2
- The get and set traps handle property reads and assignments. Reflect.get and Reflect.set let a trap pass those operations through while preserving the receiver as the value of this. section 9.2
- Other traps include 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 example proxies an emperor object: it forwards access to existing properties, supplies a response for missing reads, and rejects assignments to missing properties. section 9.2

