Sub topic 3
Traps: The Operations a Proxy Can Intercept
The previous chapter showed that a proxy is built from a target and a handler. This chapter covers the handler itself: which properties it can have, which JavaScript operations each one intercepts, and what the engine does when a trap is missing. The get and set traps are covered in detail in the next chapter, and the Reflect API after that. Here the goal is the full map.
This chapter assumes you know objects, property descriptors, prototype-chain lookup, how this works in functions, and new. It also assumes you have read the earlier chapter on internal methods such as [[Get]] and [[Set]].
The handler is a table of internal-method overrides
Every object in JavaScript supports a fixed set of internal methods. An ordinary object uses the default algorithms from the specification. A proxy is an exotic object: each of its internal methods first checks the handler for a matching function, called a trap. If the trap exists, the engine calls it. If it does not, the engine runs the same internal method on the target instead.
There are exactly 13 traps. Eleven exist on every proxy. The last two, apply and construct, only matter when the target is a function.
| Trap | Internal method | Triggered by (examples) |
|---|---|---|
| `get` | `[[Get]]` | `p.x`, `p[key]`, destructuring, reads on objects that inherit from `p` |
| `set` | `[[Set]]` | `p.x = v`, `p[key] = v`, `Object.assign(p, src)` |
| `has` | `[[HasProperty]]` | `key in p`, `with (p)`, `in` checks on objects inheriting from `p` |
| `deleteProperty` | `[[Delete]]` | `delete p.x` |
| `ownKeys` | `[[OwnPropertyKeys]]` | `Object.keys`, `Object.getOwnPropertyNames`, `Object.getOwnPropertySymbols`, `Reflect.ownKeys`, `for...in`, `{...p}`, `JSON.stringify` |
| `getOwnPropertyDescriptor` | `[[GetOwnProperty]]` | `Object.getOwnPropertyDescriptor`, `Object.hasOwn`, `hasOwnProperty`, enumerability checks in `Object.keys` |
| `defineProperty` | `[[DefineOwnProperty]]` | `Object.defineProperty`, `Object.defineProperties`, and the final step of a forwarded `set` |
| `getPrototypeOf` | `[[GetPrototypeOf]]` | `Object.getPrototypeOf`, `p instanceof C`, `__proto__` getter, `isPrototypeOf` |
| `setPrototypeOf` | `[[SetPrototypeOf]]` | `Object.setPrototypeOf`, `__proto__` setter |
| `isExtensible` | `[[IsExtensible]]` | `Object.isExtensible`, `Object.isFrozen`, `Object.isSealed` |
| `preventExtensions` | `[[PreventExtensions]]` | `Object.preventExtensions`, `Object.freeze`, `Object.seal` |
| `apply` | `[[Call]]` | `p()`, `p.call(...)`, `p.apply(...)`, `Reflect.apply(p, ...)` |
| `construct` | `[[Construct]]` | `new p()`, `Reflect.construct(p, ...)` |
The table maps traps to internal methods, not to syntax. One line of code can call several internal methods, so it can fire several traps. Most surprises with proxies come from this.
Trap signatures
Every trap receives the target as its first argument. The rest depend on the internal method being replaced.
const handler = {
get(target, property, receiver) {},
set(target, property, value, receiver) {}, // return boolean
has(target, property) {}, // return boolean
deleteProperty(target, property) {}, // return boolean
ownKeys(target) {}, // return array of strings/symbols
getOwnPropertyDescriptor(target, property) {}, // return descriptor or undefined
defineProperty(target, property, descriptor) {}, // return boolean
getPrototypeOf(target) {}, // return object or null
setPrototypeOf(target, prototype) {}, // return boolean
isExtensible(target) {}, // return boolean
preventExtensions(target) {}, // return boolean
apply(target, thisArg, argumentsList) {}, // return anything
construct(target, argumentsList, newTarget) {} // return an object
};Some details to remember:
propertyis always a string or a symbol. Numeric indexes likep[0]arrive as the string'0'.receiveringetandsetis the object the operation started on. Usually that is the proxy, but it can be an object that inherits from it. A later chapter covers why this matters.- Traps that return a boolean are reporting success. For example, if
setreturnsfalsein strict-mode code, the assignment throws aTypeError. In sloppy mode it fails silently. - Inside a trap,
thisis the handler object. You can use it to share helper methods between traps.
Watching every trap fire
The quickest way to learn the mapping is to log it. The handler below is itself a proxy. When the engine looks up a trap name on it, the handler's own get trap returns a logging function that forwards to the Reflect method of the same name. Every trap has a Reflect method with the same name and argument order, which is what makes this trick work.
const tracingHandler = new Proxy({}, {
get(_, trapName) {
return (...args) => {
const prop = typeof args[1] === 'string' ? ` ${args[1]}` : '';
console.log(`${trapName}${prop}`);
return Reflect[trapName](...args);
};
}
});
const p = new Proxy({ a: 1 }, tracingHandler);
console.log('--- read');
p.a;
console.log('--- write new property');
p.b = 2;
console.log('--- in');
'a' in p;
console.log('--- delete');
delete p.a;
console.log('--- Object.keys');
Object.keys(p);
console.log('--- getPrototypeOf');
Object.getPrototypeOf(p);Output:
--- read
get a
--- write new property
set b
getOwnPropertyDescriptor b
defineProperty b
--- in
has a
--- delete
deleteProperty a
--- Object.keys
ownKeys
getOwnPropertyDescriptor b
--- getPrototypeOf
getPrototypeOfTwo results need an explanation.
A write fires three traps. The set trap forwards with Reflect.set(target, 'b', 2, receiver), and the receiver is the proxy. The default [[Set]] algorithm creates the property on the receiver, not on the target. To do that, it asks the receiver for its existing own descriptor ([[GetOwnProperty]]) and then defines the property on it ([[DefineOwnProperty]]). The receiver is the proxy, so both steps go through the proxy's traps. This means a defineProperty trap also sees ordinary assignments, as long as set forwards with the receiver.
Object.keys fires two kinds of trap. Object.keys returns only enumerable string keys. It calls ownKeys to get every key, then calls getOwnPropertyDescriptor on each one to check whether it is enumerable. If you filter keys in ownKeys but report a descriptor as non-enumerable, or return undefined from getOwnPropertyDescriptor, the key disappears from Object.keys even though Reflect.ownKeys still lists it.
What happens when a trap is missing
The decision the engine makes for every operation looks like this:
A proxy with an empty handler, new Proxy(target, {}), behaves almost like the target itself. This makes it reasonable to write handlers with only the traps you need.
The "almost" matters, and it comes from the write example above. Even with no traps, the proxy is a separate object with its own identity, and built-ins that depend on internal slots (such as Map or Date) do not work through it. The last chapter covers those limits.
Traps are looked up on every operation
The engine does not copy traps when you create the proxy. It reads the trap from the handler each time an operation happens. Adding, replacing, or removing a trap later changes the proxy's behavior right away:
const handler = {};
const p = new Proxy({ x: 1 }, handler);
console.log(p.x); // 1, no get trap yet
handler.get = () => 'intercepted';
console.log(p.x); // 'intercepted'
delete handler.get;
console.log(p.x); // 1 againThis is valid behavior you can rely on, but it is rarely what you want in production code. Treat a handler as fixed after the proxy is created unless you have a specific reason to switch behavior at run time.
A trap must be a function, undefined, or null. If you set a trap to any other value, such as handler.get = 42, the next operation that looks it up throws a TypeError.
Function-only traps: apply and construct
apply and construct replace [[Call]] and [[Construct]]. A proxy only has those internal methods if its target has them. Putting an apply trap on a proxy whose target is a plain object does not make the proxy callable:
const notCallable = new Proxy({}, {
apply() {
return 'never runs';
}
});
console.log(typeof notCallable); // 'object'
try {
notCallable();
} catch (err) {
console.log(err instanceof TypeError); // true: notCallable is not a function
}The same rule applies to construct. An arrow function can be called but not constructed, so new on a proxy of an arrow function throws even if you define a construct trap. typeof on a proxy always matches its target: 'function' for callable targets and 'object' otherwise. To proxy something that should be callable, use a function as the target.
A function proxy still has all eleven object traps. A get trap on a proxied function intercepts fn.name, fn.length, and fn.prototype. A chapter later in this tutorial covers apply and construct in depth.
Operations no trap can intercept
Some things a proxy cannot change because no internal method is involved:
| Operation | Why it cannot be trapped |
|---|---|
| `p === target`, `p === other` | Identity comparison does not call any internal method. The proxy is always its own object. |
| `typeof p` | Decided from whether the target has `[[Call]]`. |
| `#field` access on class instances | Private fields are stored on the object itself and looked up directly, bypassing `[[Get]]`. |
| Internal slots like `[[MapData]]` | Built-in methods read slots on `this`, and a proxy has no slots. |
Object.prototype.toString.call(p) partly goes through the proxy. It reads Symbol.toStringTag with [[Get]], so a get trap can change the tag. Array.isArray(p) looks through the proxy to its target and returns true for a proxied array.
Choosing which traps to write
Start from the operations you want to change, then use the table to find every trap they reach:
- Hide a property completely. You need
getfor reads,hasforin,ownKeysfor enumeration, andgetOwnPropertyDescriptorforObject.hasOwnandObject.getOwnPropertyDescriptor. Missing any one of these leaves a way to detect the property. - Make an object read-only. Block
set,deleteProperty,defineProperty, andsetPrototypeOf. If you block onlyset,Object.defineProperty(p, ...)still writes to the target. - Log all access. Use the tracing handler pattern above, or write each trap explicitly when you need different behavior per trap.
The rule is that each trap covers one internal method, and many pieces of syntax and many library functions reach the same internal method. Check the whole path an operation takes, not just the syntax at the call site.
Exercise
Given const p = new Proxy({ a: 1, b: 2 }, tracingHandler) using the tracing handler from this chapter, which traps fire, in order, for const { a, ...rest } = p;?
Show answer
get a for the named binding. Then the rest pattern copies the remaining own enumerable properties: ownKeys, then for the key b (a is skipped because it was already bound) getOwnPropertyDescriptor b to check enumerability, then get b to read the value.
Exercise
A handler defines only a set trap that throws, intended to make the proxy read-only. Name two operations that still modify the target, and the trap that would block each.
Show answer
Object.defineProperty(p, 'x', { value: 1 }) reaches [[DefineOwnProperty]] and needs a defineProperty trap. delete p.a reaches [[Delete]] and needs a deleteProperty trap. Object.setPrototypeOf(p, other) (blocked by setPrototypeOf) and Object.preventExtensions(p) (blocked by preventExtensions) also pass through unchanged.
Exercise
You create new Proxy({}, { apply: () => 42 }) and call it. What happens, and how do you change the code so the call returns 42?
Show answer
The call throws a TypeError because the target is a plain object with no [[Call]] internal method, so the proxy is not callable and typeof reports 'object'. Use a function as the target, for example new Proxy(function () {}, { apply: () => 42 }). Calling that proxy returns 42.