Sub topic 13
Where Proxies Fall Short: Internal Slots, Private Fields, Identity, and Performance
Earlier chapters covered what a proxy can do. This chapter covers what it cannot do. A proxy intercepts the operations listed in its handler: get, set, has, ownKeys, apply, and the rest. Some JavaScript behavior does not go through those operations. When code depends on that behavior, a proxy either breaks the code or lets it skip the proxy entirely.
This chapter assumes you are comfortable with get traps, forwarding through Reflect with a receiver, classes, and this binding. You should also know how Function.prototype.bind works.
The chapter covers four limits:
- Internal slots. Built-ins such as
Mapkeep their data where a proxy cannot reach it. - Private class fields.
#fieldlookups check the object's identity and never reach a trap. - Identity. A proxy is a separate object from its target.
- Performance. Every intercepted operation costs a function call.
Internal Slots: Data the Proxy Doesn't Have
An internal slot is hidden per-object state that the specification attaches to some built-in objects. A Map stores its entries in [[MapData]]. A Date stores its time value in [[DateValue]]. A Promise has [[PromiseState]]. Typed arrays have [[ViewedArrayBuffer]]. No property access can reach these slots, so no trap can forward them.
Built-in methods check for the slot on their this value. Calling map.set(k, v) runs Map.prototype.set with this equal to map, and that method looks for [[MapData]] on this. Through a proxy, this is the proxy. The proxy has no [[MapData]], so the method throws.
const map = new Map();
const proxy = new Proxy(map, {});
try {
proxy.set('a', 1);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "Method Map.prototype.set called on incompatible receiver #<Map>"
}
const date = new Proxy(new Date(0), {});
try {
date.getTime();
} catch (err) {
console.log(err.message); // e.g. "this is not a Date object."
}The empty handler forwarded the property read correctly. The set function was found. The method call failed because of the this value it ran with.
The workaround: bind methods, read getters with the target
The fix has two parts. Bind every function to the target, and read accessors with the target as the receiver. size is an accessor on Map.prototype that also checks [[MapData]]. Passing the proxy as the receiver would fail the same way.
Binding brings in a smaller problem. Each bind call creates a new function, so proxy.set === proxy.set would be false. That matters if code compares methods or adds and removes them as event listeners. A WeakMap cache keyed by the original function keeps the identity stable:
function wrapBuiltin(obj, onAccess = () => {}) {
const boundCache = new WeakMap();
return new Proxy(obj, {
get(target, prop) {
onAccess(prop);
const value = Reflect.get(target, prop, target);
if (typeof value !== 'function') return value;
let bound = boundCache.get(value);
if (!bound) {
bound = value.bind(target);
boundCache.set(value, bound);
}
return bound;
}
});
}
const tracked = wrapBuiltin(new Map(), (prop) => console.log(`access ${String(prop)}`));
tracked.set('a', 1); // access set
console.log(tracked.get('a')); // access get, then 1
console.log(tracked.size); // access size, then 1
console.log(tracked.set === tracked.set); // truePlain arrays are the exception. Arrays keep their elements in ordinary properties. Their one exotic behavior, keeping length in sync, runs through [[DefineOwnProperty]], which a trap can forward. new Proxy([], {}).push(1) works without any binding.
Private Class Fields
Private fields (#name) work like internal slots for user-defined classes. A private field lookup such as this.#count is not a property access. It does not call [[Get]]. It checks whether that exact object was given the field by the class constructor. A proxy was never given the field, and no trap is consulted.
class Counter {
#count = 0;
increment() {
this.#count += 1;
return this.#count;
}
get value() {
return this.#count;
}
}
const counter = new Counter();
const proxy = new Proxy(counter, {});
try {
proxy.increment();
} catch (err) {
console.log(err.message);
// e.g. "Cannot read private member #count from an object whose class did not declare it"
}
try {
proxy.value; // the getter runs with this = proxy, so it fails too
} catch (err) {
console.log(err instanceof TypeError); // true
}The getter case shows that correct receiver forwarding, the technique from the receiver chapter, makes this problem worse. Reflect.get(target, 'value', receiver) runs the getter with this set to the proxy, and #count is missing on the proxy.
The workaround is the same as for built-ins. Bind methods to the target, and read getters with the target as the receiver:
class Counter {
#count = 0;
increment() { return ++this.#count; }
get value() { return this.#count; }
}
const counter = new Counter();
const proxy = new Proxy(counter, {
get(target, prop) {
const value = Reflect.get(target, prop, target);
return typeof value === 'function' ? value.bind(target) : value;
}
});
console.log(proxy.increment()); // 1
console.log(proxy.value); // 1This fix costs you the inheritance behavior from earlier chapters. If another object inherits from this proxy, its getters now run against counter instead of the inheriting object. You have to choose between private-field compatibility and receiver correctness for each wrapper.
A brand check is another source of failure. #count in obj returns false for the proxy. Static helper methods that run brand checks will reject proxies even when the methods are bound.
Identity: The Proxy Is a Different Object
new Proxy(target, handler) creates a new object. It is never === to its target, and nothing that compares identity sees through it.
const target = { id: 1 };
const proxy = new Proxy(target, {});
console.log(proxy === target); // false
const seen = new Set([target]);
console.log(seen.has(proxy)); // false
const meta = new WeakMap([[target, 'info']]);
console.log(meta.get(proxy)); // undefined
console.log(Array.isArray(new Proxy([], {}))); // true: IsArray looks through proxies
console.log(proxy instanceof Object); // true: uses the getPrototypeOf trapThe table shows how common checks behave:
| Check | Sees through the proxy? | Why |
|---|---|---|
| `===`, `Object.is` | No | They compare object identity |
| `Set`, `Map`, `WeakMap` keys | No | Keys are matched by identity |
| `Array.isArray` | Yes | The spec's IsArray follows the proxy to its target |
| `instanceof` | Partly | It walks `getPrototypeOf`, which the trap controls |
| `Object.prototype.toString` | Partly | It returns `[object Array]` for array targets, and otherwise reads `Symbol.toStringTag` through `get` |
| `structuredClone`, `postMessage` | No | Proxies cannot be cloned and throw `DataCloneError` |
| `JSON.stringify` | Yes | It uses `ownKeys`, `getOwnPropertyDescriptor`, and `get` |
Three practical consequences follow:
- Leaked targets bypass the proxy. If any code keeps a reference to the raw target, it can read and write without passing through your traps. A validation proxy only protects the object if nobody else holds the target. Create the target inside a factory and return only the proxy.
- Mixed references cause bugs. If one module caches the target and another caches the proxy, identity-based lookups disagree. Pick one, normally the proxy, and use it everywhere. Libraries such as Vue keep a
WeakMapfrom target to proxy so that wrapping the same object twice returns the same proxy. - You can't detect a proxy. Standard JavaScript has no
isProxyfunction, by design. Node.js exposesutil.types.isProxyfor debugging. Don't build program logic on it.
Performance
A property read on a plain object is one of the most heavily optimized operations in a JavaScript engine. Inline caches remember an object's shape and turn obj.x into a near-direct memory load. A proxy prevents that. Every intercepted operation calls your trap function, passes its arguments, often calls a Reflect method, and then checks the result against the invariants.
The overhead also grows in ways that are easy to miss:
- One
for...inloop orObject.keyscall can triggerownKeys, thengetOwnPropertyDescriptoronce for each key. JSON.stringify(proxy)triggersgetonce for each property, plus a read oftoJSON.- A deep or recursive proxy (one that wraps every nested object as it is read) allocates or looks up a proxy on every access.
Measure in your own engine instead of trusting general figures:
const plain = { x: 1 };
const proxied = new Proxy({ x: 1 }, {
get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
}
});
function bench(label, obj) {
const start = performance.now();
let total = 0;
for (let i = 0; i < 10_000_000; i++) total += obj.x;
console.log(`${label}: ${(performance.now() - start).toFixed(1)} ms (${total})`);
}
bench('plain', plain);
bench('proxy', proxied);In current engines, the proxy loop is usually many times slower. The exact ratio depends on the engine, the trap body, and whether the plain loop gets optimized away.
These guidelines follow:
- Proxies are fine at boundaries: configuration objects, API facades, debugging wrappers, and state that changes at human speed.
- Keep proxies out of hot inner loops. Read values into local variables before the loop, or work on the raw target inside trusted code.
- Keep trap bodies small. Avoid allocating objects inside
get.
Choosing a Workaround
| Symptom | Cause | Workaround | Cost |
|---|---|---|---|
| `incompatible receiver` on Map, Set, Date, or Promise | Internal slot missing on the proxy | Bind methods to the target, read getters with the target as receiver | Internal operations bypass traps |
| `Cannot read private member` | Brand check on `#field` | Bind methods and getters to the target | Inheritance through the proxy breaks |
| `Set` or `WeakMap` lookup misses | Proxy and target are different objects | Use one reference consistently, and cache target to proxy | Bookkeeping |
| `DataCloneError` | Proxies are not cloneable | Clone a plain snapshot such as `structuredClone({ ...proxy })` | A copy, not a live view |
| Slow hot path | A trap call on every operation | Unwrap before loops, keep traps small | Less interception coverage |
If a design needs several of these workarounds, check whether a proxy is the right tool. A subclass, an explicit wrapper class with named methods, or getters and setters defined with Object.defineProperty can be faster and simpler.
Exercise
You wrap a Set with new Proxy(new Set(), { get(t, p, r) { return Reflect.get(t, p, r); } }). Calling proxy.add(1) throws, and reading proxy.size also throws. Explain both failures and give a get trap that fixes them.
Show answer
add runs with this set to the proxy, which has no [[SetData]] slot. size is an accessor, and passing the proxy as the receiver runs its getter with this set to the proxy, which fails the same slot check. Fix: get(t, p) { const v = Reflect.get(t, p, t); return typeof v === 'function' ? v.bind(t) : v; }. This reads accessors with the target as receiver and binds methods to the target. Add a WeakMap cache if method identity matters.
Exercise
A validation proxy rejects negative balance values. A teammate's module stores the original object in a cache before it is wrapped, and later sets balance = -50 through the cached reference. What happens, and how do you prevent it?
Show answer
The write succeeds and skips validation, because the cached reference is the raw target and no trap runs. Prevent it by creating the target inside a factory function that returns only the proxy, so no outside code ever holds the target.
Exercise
Why does Reflect.get(target, prop, receiver), the correct choice for plain objects, break a getter that reads a private field, and what do you give up by switching to Reflect.get(target, prop, target)?
Show answer
Passing the proxy as the receiver runs the getter with this set to the proxy, and the private field brand check fails on the proxy. Passing the target makes the check pass. The trade-off is that objects inheriting from the proxy (via Object.create(proxy)) now see the getter run against the target, not against themselves, so inherited getters return the target's data.