Sub topic 5
Reflect: The Default Behavior for Every Trap
This chapter assumes you know how a Proxy is built from a target and a handler, and that each trap maps to an internal method such as [[Get]] or [[Set]]. You should also be comfortable with property descriptors and Function.prototype.apply.
When you write a trap, you usually want to do a little extra work and then let the operation go ahead as it normally would. Reflect is the built-in object that gives you "as it normally would" for every trap.
What Reflect Is
Reflect is a plain namespace object, like Math. You cannot call it or use it with new. It holds 13 static methods, and each one has the same name and the same parameters as a proxy trap. Each method performs the matching internal method on an object directly.
| Trap | Reflect method | Ordinary syntax it mirrors |
|---|---|---|
| `get` | `Reflect.get(target, prop, receiver)` | `obj[prop]` |
| `set` | `Reflect.set(target, prop, value, receiver)` | `obj[prop] = value` |
| `has` | `Reflect.has(target, prop)` | `prop in obj` |
| `deleteProperty` | `Reflect.deleteProperty(target, prop)` | `delete obj[prop]` |
| `ownKeys` | `Reflect.ownKeys(target)` | all own keys, including symbols |
| `apply` | `Reflect.apply(fn, thisArg, args)` | `fn.apply(thisArg, args)` |
| `construct` | `Reflect.construct(C, args, newTarget)` | `new C(...args)` |
| `defineProperty` | `Reflect.defineProperty(target, prop, desc)` | `Object.defineProperty` |
| `getOwnPropertyDescriptor` | `Reflect.getOwnPropertyDescriptor(target, prop)` | `Object.getOwnPropertyDescriptor` |
| `getPrototypeOf` / `setPrototypeOf` | `Reflect.getPrototypeOf` / `Reflect.setPrototypeOf` | `Object.getPrototypeOf` / `Object.setPrototypeOf` |
| `isExtensible` / `preventExtensions` | `Reflect.isExtensible` / `Reflect.preventExtensions` | `Object.isExtensible` / `Object.preventExtensions` |
Because the signatures match, forwarding is mechanical. You pass the trap's arguments straight through.
Booleans Instead of Exceptions
Several Object methods throw on failure. Their Reflect versions return false instead, and that is the value traps such as set, deleteProperty, and defineProperty are expected to return.
const obj = Object.preventExtensions({});
console.log(Reflect.defineProperty(obj, 'x', { value: 1 })); // false
try {
Object.defineProperty(obj, 'x', { value: 1 });
} catch (err) {
console.log(err instanceof TypeError); // true
}If a set trap returns false, the engine decides what happens next. In strict mode, the assignment throws a TypeError. In sloppy mode, it fails silently. Returning the result of Reflect.set keeps that behavior the same as it is for an unproxied object.
Forwarding Every Trap Generically
The trap names and the Reflect method names are identical, so you can build a handler that logs every trap without writing any of them by hand:
function logged(target) {
const handler = Object.fromEntries(
Object.getOwnPropertyNames(Reflect).map((name) => [
name,
(...args) => {
console.log(name);
return Reflect[name](...args);
}
])
);
return new Proxy(target, handler);
}
const p = logged({ a: 1 });
p.a; // logs "get"
'a' in p; // logs "has"
Object.keys(p); // logs "ownKeys", then "getOwnPropertyDescriptor"The last line shows something useful. Object.keys calls [[OwnPropertyKeys]] and then checks each key's descriptor to see whether it is enumerable. A logging proxy like this one is a quick way to find out which internal methods a given piece of syntax actually triggers.
Reflect vs. Doing It Yourself
You could write return target[prop] in a get trap, and for simple objects you would get the same result. The two differ in three ways:
- Return values.
Reflectreports success as a boolean, which matches what traps must return. - Completeness.
Reflect.ownKeysreturns string keys and symbol keys, including non-enumerable ones.Object.keysreturns only enumerable string keys. - The receiver.
Reflect.getandReflect.setaccept areceiverargument, which setsthisinside getters and setters.target[prop]has no way to pass it. The next chapter explains why this matters.
Exercise
A set trap contains only target[prop] = value;. The proxy is used in an ES module, and every assignment throws a TypeError. Why does this happen, and what one-line change fixes it?
Show answer
ES modules run in strict mode. The trap returns undefined, which is falsy, so the engine treats every assignment as a failure and throws. Replace the body with return Reflect.set(target, prop, value, receiver); (with receiver added to the trap's parameters), so the trap returns true when the write succeeds.
Exercise
You run Object.keys(p) on a proxy whose handler defines only an ownKeys trap, and the trap returns Reflect.ownKeys(target). The target has a symbol key and a non-enumerable string key. Will either of them appear in the result?
Show answer
No. The trap passes all keys to the engine, but Object.keys then keeps only string keys whose descriptors are enumerable. The symbol and the non-enumerable key are both dropped.