Sub topic 2
Your First Proxy: Target and Handler
This chapter assumes you are comfortable with JavaScript objects and property access, prototypes, functions and this, and ES6 syntax such as arrow functions and template literals. You should also have the idea from the previous chapter that every operation on an object, such as reading a property, runs one of the object's internal methods, like [[Get]] or [[Set]].
A Proxy lets you supply your own code for those internal methods. This chapter covers the two pieces every proxy is built from, how they relate to each other, and the behavior of a proxy before you customize anything.
The Constructor
You create a proxy with new Proxy(target, handler):
- The target is the object the proxy wraps. Any operation you don't customize goes to the target.
- The handler is an ordinary object whose methods, called traps, intercept operations. A trap is a method with a specific name, such as
getorset, that the engine calls in place of the matching internal method.
The constructor returns a new object, the proxy. Code that uses the proxy cannot see its target or handler. It only sees an object that behaves as the handler says it should.
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"When proxy.greeting runs, the engine invokes the proxy's [[Get]] internal method. A proxy's [[Get]] checks whether the handler has a get method. Here it does, so the engine calls handler.get with three arguments: the target, the property key 'greeting', and the receiver, which is the object the access started on (here, the proxy). The trap logs the access and then hands the read on to the target with Reflect.get. A later chapter covers Reflect in detail. For now, treat Reflect.get(target, prop, receiver) as "do the normal read on the target."
String(prop) is there because property keys can be symbols, and a template literal throws a TypeError when it tries to convert a symbol implicitly. Logging traps receive symbol keys more often than you'd think, for example Symbol.toPrimitive during string conversion or Symbol.iterator during spreading.
How an Operation Flows Through a Proxy
Each time an operation reaches the proxy, the engine makes the same decision.
Two things follow from this picture:
- The handler is optional per operation. A handler with only a
gettrap customizes reads, and every other operation (writes, deletes,in, key listing, and so on) goes straight to the target. - The trap decides what happens. It can forward to the target, return something else, or throw. Nothing forces a trap to touch the target at all, apart from the invariant rules covered in a later chapter.
The Empty Handler: A Transparent Wrapper
With an empty handler, a proxy forwards every operation to its target:
const target = { count: 0 };
const proxy = new Proxy(target, {});
proxy.count = 5; // forwarded [[Set]]
console.log(target.count); // 5: the write landed on the target
target.extra = 'added directly';
console.log(proxy.extra); // 'added directly': reads see target changes
delete proxy.count;
console.log('count' in target); // false
console.log(Object.keys(proxy)); // ['extra']
console.log(JSON.stringify(proxy)); // {"extra":"added directly"}
console.log(Object.getPrototypeOf(proxy) === Object.prototype); // trueThe proxy stores no data of its own. All state lives in the target, and the proxy is a view onto it. This has a consequence that matters for every pattern later in the tutorial:
function createCounter() {
const state = { value: 0 }; // only reachable through the proxy
return new Proxy(state, {
set(target, prop, value, receiver) {
if (prop !== 'value') throw new TypeError(`unknown field ${String(prop)}`);
return Reflect.set(target, prop, value, receiver);
}
});
}
const counter = createCounter();
counter.value = 1; // allowed
// counter.other = 2; // TypeError: unknown field otherIdentity: The Proxy Is a Different Object
A proxy is a separate object from its target, even when it behaves identically:
const target = {};
const proxy = new Proxy(target, {});
console.log(proxy === target); // false
const seen = new Set([target]);
console.log(seen.has(proxy)); // falseSet, Map, WeakMap, and === all compare identity, so a proxy and its target count as two keys. If part of your code registers the target and another part looks it up with the proxy, the lookup fails. The final chapter returns to identity problems. For now, pick one of the two and use it consistently.
What the Proxy Reports About Itself
Several checks look at the target to decide what kind of object the proxy is:
| Check | Plain object target | Array target | Function target |
|---|---|---|---|
| `typeof proxy` | `'object'` | `'object'` | `'function'` |
| `Array.isArray(proxy)` | `false` | `true` | `false` |
| `proxy()` callable | no, `TypeError` | no, `TypeError` | yes |
| `new proxy()` allowed | no | no | yes, if the target is a constructor |
The engine fixes typeof and callability when the proxy is created, based on the target. No trap can make a proxy of a plain object callable. If you want a callable proxy, the target must be a function. Array.isArray looks through the proxy to its target on purpose, so proxied arrays still pass array checks in libraries.
const list = new Proxy([1, 2, 3], {});
console.log(Array.isArray(list)); // true
console.log(list.length); // 3
console.log([...list]); // [1, 2, 3]
const fn = new Proxy(function add(a, b) { return a + b; }, {});
console.log(typeof fn); // 'function'
console.log(fn(2, 3)); // 5Constructor Rules and Common Errors
Proxy has some rules that catch people out the first time.
Both arguments must be objects
The target and handler must each be an object or a function. Primitives throw:
try {
new Proxy('text', {});
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
new Proxy({}, null);
} catch (err) {
console.log(err instanceof TypeError); // true
}To wrap a primitive value, put it inside an object first, for example { value: 'text' }.
You must call it with new
Proxy({}, {}) without new throws a TypeError. You also can't subclass it in the usual way: Proxy has no prototype property, because proxies are not instances of a Proxy class. They copy the shape and prototype of their target. This means instanceof Proxy throws rather than returning false:
const proxy = new Proxy({}, {});
console.log(Proxy.prototype); // undefined
try {
proxy instanceof Proxy;
} catch (err) {
console.log(err instanceof TypeError); // true
}Trap names must be spelled exactly
The engine looks up traps by name. A misspelled trap such as gett or deleteproperty is just an ordinary method that never gets called, and the operation falls through to the target without any error. When a trap seems to have no effect, check its spelling first. The next chapter lists every valid trap name.
The Handler Is Consulted on Every Operation
The engine doesn't copy the traps when you create the proxy. It looks up the trap on the handler each time an operation happens. So if you change the handler later, the proxy's behavior changes too:
const handler = {};
const proxy = new Proxy({ a: 1 }, handler);
console.log(proxy.a); // 1: no get trap yet, forwarded to target
handler.get = () => 'intercepted';
console.log(proxy.a); // 'intercepted'
delete handler.get;
console.log(proxy.a); // 1 againThis is occasionally useful, for example to switch tracing on and off at runtime. More often it's a hazard: if several proxies share one handler object, a change to that handler affects all of them. When you build proxies in a factory, create a fresh handler for each proxy unless you specifically want them to share behavior.
The engine calls traps with this set to the handler. That lets one trap call helper methods or read configuration stored on the handler:
const handler = {
prefix: '[trace]',
log(message) {
console.log(`${this.prefix} ${message}`);
},
get(target, prop, receiver) {
this.log(`read ${String(prop)}`); // this === handler
return Reflect.get(target, prop, receiver);
}
};
const traced = new Proxy({ x: 10 }, handler);
console.log(traced.x); // "[trace] read x", then 10If you write a trap as an arrow function, it won't get the handler as this. That's fine for self-contained traps, but use method syntax when the trap needs other handler members.
Proxies Can Wrap Proxies
A target can be any object, including another proxy. Each layer runs its own trap and then forwards to the next layer inward:
const base = { value: 42 };
const inner = new Proxy(base, {
get(target, prop, receiver) {
console.log('inner');
return Reflect.get(target, prop, receiver);
}
});
const outer = new Proxy(inner, {
get(target, prop, receiver) {
console.log('outer');
return Reflect.get(target, prop, receiver);
}
});
console.log(outer.value); // "outer", "inner", then 42Layering lets you combine independent concerns, such as logging on the outside and validation on the inside. Every layer adds a function call to each operation, though, so deep stacks cost performance on hot paths.
Exercise
Given const t = { n: 1 }; const p = new Proxy(t, {}); p.n = 2; t.m = 3;, what do t.n, p.m, and p === t evaluate to, and why?
Show answer
t.n is 2, because the empty handler forwards the write on p to the target t. p.m is 3, because reads through the proxy see whatever is currently on the target. p === t is false, because a proxy is a separate object with its own identity even when it forwards everything.
Exercise
A teammate writes new Proxy(obj, { Get(t, k) { return 'x'; } }) and finds that reads return the real values instead of 'x'. No error is thrown. What is wrong?
Show answer
Trap names are case-sensitive. The engine looks for a method named get, so Get is never called and every read falls through to the target. Renaming the method to get fixes it.
Exercise
Why does typeof new Proxy({}, { apply() { return 1; } }) return 'object', and why does calling the proxy throw a TypeError even though it has an apply trap?
Show answer
Whether a proxy is callable, and so what typeof reports, is fixed at creation from the target. The target here is a plain object, which can't be called, so the proxy can't be called either and the apply trap never runs. To intercept calls, the target must be a function.
Exercise
Write a function makeReadLogger(obj) that returns a proxy logging each property read as "read <key>" and returning the real value. Make sure reading a symbol-keyed property does not throw.
Show answer
function makeReadLogger(obj) { return new Proxy(obj, { get(target, prop, receiver) { console.log(read ${String(prop)}); return Reflect.get(target, prop, receiver); } }); } The String(prop) call converts symbol keys explicitly. Interpolating a symbol directly in a template literal throws a TypeError.