new Proxy and get/set traps
new Proxy(target, handler)
handler.get(target, property, receiver)
handler.set(target, property, value, receiver)A get or set trap can log or rewrite an operation. Invariant violations, such as changing a non-writable, non-configurable value, throw TypeError.
| Parameter | Description |
|---|---|
target | The object that operations are forwarded to when a trap does not override them. |
handler | An object that may define traps. An omitted trap is forwarded to the target. |
receiver | The object that initiated the get or set, often the proxy itself, used as this for accessors when forwarded with Reflect. |
Returns: The Proxy object. A get trap returns the property value. A set trap should return a boolean, as Reflect.set does.
Throws
TypeError— Thrown when a trap result violates an invariant, or when new Proxy is called with a non-object target or handler.
const logs = [];
const data = { n: 1 };
const proxy = new Proxy(data, {
get(target, key, receiver) {
logs.push(`get:${String(key)}`);
return Reflect.get(target, key, receiver);
},
set(target, key, value, receiver) {
logs.push(`set:${String(key)}=${value}`);
return Reflect.set(target, key, value, receiver);
},
});
proxy.n = 2;
console.log(proxy.n, data.n, logs.join(","));
const locked = {};
Object.defineProperty(locked, "x", { value: 1, writable: false, configurable: false });
const broken = new Proxy(locked, {
get() {
return 2;
},
});
try {
console.log(broken.x);
} catch (error) {
console.log(error.name);
}Expected output
2 2 set:n=2,get:n
TypeErrorRelated: Built-in private slots, Reflect.get and set, Official Proxy