Sub topic 2
Your First Proxy: Target and Handler
This chapter assumes you know JavaScript objects and properties, how this works in functions, and ES6 syntax such as arrow functions and template literals. You should also have read the previous chapter on internal methods like [[Get]] and [[Set]], because a proxy works by hooking into those operations.
The two parts of a proxy
You create a proxy with the Proxy constructor:
const proxy = new Proxy(target, handler);Each argument has one job:
| Part | What it is | Role |
|---|---|---|
| `target` | Any object, including arrays, functions, and other proxies | The object the proxy stands in front of. Operations reach it by default. |
| `handler` | A plain object | Holds *trap* functions, which are named methods that intercept specific operations. |
| return value | A new proxy object | The object your code uses in place of the target. |
When code performs an operation on the proxy, such as reading a property, the engine checks the handler for the trap that matches that operation. If the trap exists, the engine calls it. If it does not, the engine sends the operation straight to the target.
An empty handler: a transparent proxy
With an empty handler, the proxy forwards everything. Reads, writes, and deletions all land on the target.
const target = { greeting: 'hello' };
const proxy = new Proxy(target, {});
console.log(proxy.greeting); // 'hello'
proxy.farewell = 'bye';
console.log(target.farewell); // 'bye' (the write reached the target)
delete proxy.greeting;
console.log('greeting' in target); // false
console.log(proxy === target); // falseThe last line matters. The proxy is a separate object with its own identity. The target is not changed or wrapped in place. Code that still holds a reference to target can skip the proxy completely. If you want every access to go through the proxy, hand out only the proxy and keep the target private.
Adding a first trap
A trap is a handler method named after the operation it intercepts. The get trap runs on every property read:
const target = { greeting: 'hello' };
const handler = {
get(target, prop, receiver) {
console.log(`get ${String(prop)}`);
return Reflect.get(target, prop, receiver);
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.greeting); // logs "get greeting", then "hello"The trap receives the target, the property key, and a receiver. Reflect.get performs the normal read, so the trap adds logging without changing the result. Later chapters cover the full list of traps, the Reflect API, and why you pass receiver along. For now, note that String(prop) is there because property keys can be symbols, and a symbol in a template literal throws a TypeError.
Common errors
- Forgetting
new. CallingProxy(target, handler)throwsTypeError: Constructor Proxy requires 'new'. - Using a primitive as the target or handler.
new Proxy(42, {})throws, because both arguments must be objects. - Misspelling a trap name. A handler method called
Getorgettis just an ordinary property. The engine never calls it, so the proxy silently forwards to the target. - Expecting the target to be protected. The proxy only controls access that goes through the proxy. Direct references to the target skip it.
What a proxy looks like from outside
A proxy takes on the outward type of its target. typeof returns 'function' for a proxy around a function and 'object' otherwise. Array.isArray(new Proxy([], {})) returns true. This lets a proxy stand in for its target in most code, though some built-in objects behave differently, as a later chapter explains.
Exercise
Given const t = { n: 1 }; const h = {}; const p = new Proxy(t, h); h.get = () => 99;, what do p.n and t.n evaluate to, and why?
Show answer
p.n is 99 and t.n is 1. The engine reads traps from the handler at the moment each operation runs, so the get trap added after construction intercepts the read through p. Reading t.n directly never goes through the proxy, so it returns the real value.
Exercise
After const p = new Proxy({}, {}); p.x = 5;, where is x stored, and is p equal to the original object?
Show answer
x is stored on the target, because an empty handler forwards the write. p is not equal to the target: the proxy is a distinct object, so a === comparison between them returns false.