Sub topic 9
Descriptor, Prototype, and Extensibility Traps
The get, set, has, deleteProperty, and ownKeys traps cover the operations most code uses every day. Six more traps handle the lower-level operations: defining properties, reading property descriptors, reading and changing the prototype, and controlling extensibility. You will reach for them less often. They still matter, because ordinary-looking code such as obj.x = 1, Object.keys(obj), Object.freeze(obj), and obj instanceof Foo calls them behind the scenes.
This chapter assumes you know property descriptors (value, writable, enumerable, configurable, get, set), prototype-chain lookup, and the Reflect forwarding pattern from earlier chapters.
The Six Traps at a Glance
Each trap maps to one internal method and has a Reflect method with the same name and signature.
| Trap | Internal method | Common triggers | Must return |
|---|---|---|---|
| `defineProperty(target, prop, desc)` | `[[DefineOwnProperty]]` | `Object.defineProperty`, assignment that creates or updates a property, `Object.freeze`/`seal` | boolean |
| `getOwnPropertyDescriptor(target, prop)` | `[[GetOwnProperty]]` | `Object.getOwnPropertyDescriptor`, `Object.keys`, `Object.entries`, `JSON.stringify`, spread, `Object.hasOwn` | descriptor object or `undefined` |
| `getPrototypeOf(target)` | `[[GetPrototypeOf]]` | `Object.getPrototypeOf`, `instanceof`, `isPrototypeOf`, `__proto__` getter | object or `null` |
| `setPrototypeOf(target, proto)` | `[[SetPrototypeOf]]` | `Object.setPrototypeOf`, `__proto__` setter | boolean |
| `isExtensible(target)` | `[[IsExtensible]]` | `Object.isExtensible`, `Object.isFrozen`, `Object.isSealed` | boolean |
| `preventExtensions(target)` | `[[PreventExtensions]]` | `Object.preventExtensions`, `Object.freeze`, `Object.seal` | boolean |
The boolean-returning traps follow the convention from the Reflect chapter. Returning false means "the operation failed." Object.defineProperty, Object.setPrototypeOf, and Object.preventExtensions turn a false into a TypeError. The matching Reflect methods hand you the false directly.
Watching the Hidden Calls
The fastest way to learn these traps is to log them. Because every trap's parameters match its Reflect method, one loop can build a full logging handler.
const log = [];
const handler = {};
for (const name of [
'defineProperty', 'getOwnPropertyDescriptor', 'getPrototypeOf',
'setPrototypeOf', 'isExtensible', 'preventExtensions', 'ownKeys'
]) {
handler[name] = (...args) => {
log.push(name);
return Reflect[name](...args);
};
}
const p = new Proxy({ a: 1 }, handler);
p.b = 2;
console.log(log); // ['getOwnPropertyDescriptor', 'defineProperty']
log.length = 0;
Object.keys(p);
console.log(log); // ['ownKeys', 'getOwnPropertyDescriptor', 'getOwnPropertyDescriptor']
log.length = 0;
p instanceof Object;
console.log(log); // ['getPrototypeOf']
log.length = 0;
Object.freeze(p);
console.log(log);
// ['preventExtensions', 'ownKeys',
// 'getOwnPropertyDescriptor', 'defineProperty',
// 'getOwnPropertyDescriptor', 'defineProperty']Several of these results are worth spelling out:
- Assignment reaches
defineProperty. The handler has nosettrap, sop.b = 2falls through to the target's ordinary[[Set]], with the proxy as receiver. Ordinary[[Set]]asks the receiver whether it already ownsb(thegetOwnPropertyDescriptortrap) and then defines the property on the receiver (thedefinePropertytrap). Object.keyschecks enumerability. It gets the key list fromownKeys, then reads each key's descriptor to filter out non-enumerable keys.instanceofwalks the prototype chain through the proxy. It calls[[GetPrototypeOf]]on the proxy, so the trap runs.Object.freezeis a sequence of operations. It prevents extensions, lists the keys, then redefines each property as non-configurable and non-writable.
defineProperty: Guarding How Properties Are Created
The defineProperty trap gets the target, the key, and a descriptor. The engine normalizes that descriptor before your trap sees it. The trap receives a fresh object containing only the standard descriptor fields that were present, and any custom fields are dropped.
Which fields are present depends on how the operation started:
const seen = new Proxy({}, {
defineProperty(target, prop, desc) {
console.log(prop, desc);
return Reflect.defineProperty(target, prop, desc);
}
});
seen.x = 1;
// x { value: 1, writable: true, enumerable: true, configurable: true }
seen.x = 2;
// x { value: 2 }
Object.defineProperty(seen, 'y', { value: 3, extra: 'ignored' });
// y { value: 3 }When an assignment creates a property, the descriptor is complete. When it updates an existing property, the descriptor contains only value. Validation code that checks desc.writable === true will therefore reject ordinary updates. Check for the presence of a field before you test its value.
Here is a handler that bans accessor properties:
const dataOnly = new Proxy({}, {
defineProperty(target, prop, desc) {
if ('get' in desc || 'set' in desc) {
return false;
}
return Reflect.defineProperty(target, prop, desc);
}
});
dataOnly.x = 1; // fine
console.log(Reflect.defineProperty(dataOnly, 'z', { get() { return 1; } })); // false
try {
Object.defineProperty(dataOnly, 'y', { get() { return 2; } });
} catch (err) {
console.log(err instanceof TypeError); // true
}getOwnPropertyDescriptor: Shaping What Introspection Sees
This trap returns a descriptor object or undefined. The engine validates the result, fills in missing fields with defaults, and gives the caller a new object. Returning a custom object therefore cannot leak extra fields to the caller.
Many APIs that look at "own enumerable properties" read descriptors, so this trap can change what they report. The next example marks underscore-prefixed properties as non-enumerable without touching the target:
const record = new Proxy({ _id: 7, name: 'Ada' }, {
getOwnPropertyDescriptor(target, prop) {
const desc = Reflect.getOwnPropertyDescriptor(target, prop);
if (desc && typeof prop === 'string' && prop.startsWith('_')) {
return { ...desc, enumerable: false };
}
return desc;
}
});
console.log(Object.keys(record)); // ['name']
console.log(JSON.stringify(record)); // {"name":"Ada"}
console.log(Reflect.ownKeys(record)); // ['_id', 'name']
console.log(record._id); // 7This approach differs from the ownKeys filtering in the earlier chapter. With this trap, the key still exists. It appears in Reflect.ownKeys, it can be read directly, and '_id' in record is still true. It is only reported as non-enumerable. Changing enumerable works here because the real property is configurable. The engine will not let you misreport a non-configurable property, which the next chapter covers.
getPrototypeOf and setPrototypeOf
The getPrototypeOf trap controls what Object.getPrototypeOf, instanceof, and isPrototypeOf report. The setPrototypeOf trap can refuse prototype changes by returning false.
class Animal {}
class Robot {
beep() { return 'beep'; }
}
const pet = new Proxy(new Animal(), {
getPrototypeOf() {
return Robot.prototype;
},
setPrototypeOf() {
return false;
}
});
console.log(pet instanceof Robot); // true
console.log(pet instanceof Animal); // false
console.log(pet.beep); // undefined
console.log(Reflect.setPrototypeOf(pet, null)); // false
try {
Object.setPrototypeOf(pet, null);
} catch (err) {
console.log(err instanceof TypeError); // true
}The pet.beep line shows the main gotcha. Property lookup does not call getPrototypeOf on the proxy. Without a get trap, pet.beep forwards to the target's [[Get]], which walks the target's real chain (Animal.prototype, then Object.prototype). The trap changes what reflection reports and leaves inheritance alone. If you want reads to follow the reported prototype, you must also write a get trap, plus has for consistency.
Two more details apply:
Object.create(proxy)does not call either trap. It uses the proxy as the new object's prototype directly.- The
getPrototypeOftrap can only lie while the target is extensible. Once the target is non-extensible, the trap must return the target's actual prototype or the engine throws.
isExtensible and preventExtensions
These two traps have the tightest rules. isExtensible must return the same answer as Reflect.isExtensible(target). No other result is allowed. preventExtensions may return true only if the target really is non-extensible afterward.
Within those rules, you can still refuse. A trap that returns false produces an object that cannot be frozen, sealed, or locked:
const unfreezable = new Proxy({}, {
preventExtensions() {
return false;
}
});
console.log(Reflect.preventExtensions(unfreezable)); // false
try {
Object.freeze(unfreezable);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Object.isExtensible(unfreezable)); // trueThis is useful for objects that must stay mutable, such as a shared configuration store that a third-party library might otherwise try to freeze.
Lying in either direction fails:
const claimsLocked = new Proxy({}, {
isExtensible() {
return false;
}
});
try {
Object.isExtensible(claimsLocked);
} catch (err) {
console.log(err instanceof TypeError); // true: result must match the target
}
const fakeLock = new Proxy({}, {
preventExtensions() {
return true; // claims success without locking the target
}
});
try {
Object.preventExtensions(fakeLock);
} catch (err) {
console.log(err instanceof TypeError); // true
}The fix for fakeLock is to forward with return Reflect.preventExtensions(target);. That call locks the target, so the true it returns is accurate.
Choosing the Right Trap
| Goal | Trap to use | Why |
|---|---|---|
| Validate every new or changed property, including `Object.defineProperty` | `defineProperty` | `set` does not see `Object.defineProperty` calls |
| Validate only plain assignments | `set` | Simpler arguments, and it receives the receiver |
| Hide keys from `Object.keys` and `JSON.stringify` while leaving them readable | `getOwnPropertyDescriptor` | Changes enumerability only |
| Hide keys from all key listing | `ownKeys` (with `has`) | Removes the key from the list |
| Make `instanceof` report a different class | `getPrototypeOf` | Does not change lookup, so add `get` if needed |
| Stop freezing, sealing, or prototype swaps | `preventExtensions`, `setPrototypeOf` returning `false` | Refusal is always allowed |
Exercise
Using the logging handler from "Watching the Hidden Calls" on a fresh proxy of { a: 1 }, what does log contain after Object.seal(p)? How does it differ from Object.freeze(p)?
Show answer
['preventExtensions', 'ownKeys', 'defineProperty']. Sealing redefines each key with { configurable: false } without reading the existing descriptor first. Freezing must know whether each property is a data or an accessor property, because only data properties get writable: false, so it calls getOwnPropertyDescriptor before each defineProperty.
Exercise
A proxy's getPrototypeOf trap returns Robot.prototype, and the target is a plain Animal instance. Why does proxy instanceof Robot return true while proxy.beep (a Robot method) is undefined, and what must you add to make proxy.beep work?
Show answer
instanceof calls [[GetPrototypeOf]] on the proxy, so it sees the trap's answer. Property reads without a get trap forward to the target's [[Get]], which walks the target's real prototype chain and never consults the trap. Add a get trap that falls back to Reflect.get(Robot.prototype, prop, receiver) when the target does not have the property, and a matching has trap so the in operator agrees.
Exercise
Write a defineProperty trap that rejects any attempt to make a property non-configurable, but still allows ordinary assignments such as obj.x = 1 and obj.x = 2.
Show answer
defineProperty(target, prop, desc) { if ('configurable' in desc && desc.configurable === false) return false; return Reflect.defineProperty(target, prop, desc); }. Testing for presence matters. An update assignment passes only { value }, and creating a property by assignment passes configurable: true, so both are allowed. Object.defineProperty(obj, 'y', { value: 1 }) omits configurable and would create a non-configurable property by default, so a stricter version also rejects new properties defined without configurable: true. Check whether the key exists with Reflect.getOwnPropertyDescriptor(target, prop) first.