JavaScript
The Reflect API
Learn the Reflect object and how to apply default behavior inside a trap.
What is Reflect?
Reflect is a built-in object that provides methods for object operations. These methods share the exact names and behaviors of Proxy traps, so it is the clean way to call the default behavior from inside a trap.
Reflect.get(target, prop);
Reflect.set(target, prop, value);
Reflect.get reads a property, Reflect.set writes a value and returns true on success, and Reflect.has gives the same result as the in operator. Used together with Proxy, your code stays short and consistent.
Reflect inside a trap
When you write a trap, you often want to intercept an operation and then apply it unchanged. Reflect does this in a single line.
const handler = {
get(target, prop) {
return Reflect.get(target, prop);
}
};
Add a console.log line here and you get a logging trap, or add a condition to validate. Even without the Reflect call the trap still works; with it, the intent is clearer and the behavior stays identical to a plain proxy.
Exercise get and set traps with Reflect
Define an object named user with a name property. Inside a handler, write the get and set traps: both apply the default behavior through a Reflect call (get returns Reflect.get(target, prop), set returns Reflect.set(target, prop, value)). Create a proxy variable with new Proxy(user, handler). Assign proxy.age = 28 and log console.log(proxy.name).
Show example solution
const user = { name: 'Ayşe' };
const handler = {
get(target, prop) {
return Reflect.get(target, prop);
},
set(target, prop, value) {
return Reflect.set(target, prop, value);
}
};
const proxy = new Proxy(user, handler);
proxy.age = 28;
console.log(proxy.name);
Test yourself
-
Match the Reflect methods
- Reflect.get
- reads a property
- Reflect.set
- writes a property
- Reflect.has
- existence check
- Reflect
- trap helper
-
What does Reflect.get(target, prop) return?
- true or false
- undefined
- a new Proxy
- the value of prop on target
Show answer
the value of prop on target — Correct! Reflect.get returns the value of the prop property on the target object.
-
Use Reflect inside the get trap
get(target, prop) {
return ____;
}
Show answer
get(target, prop) {
return Reflect.get(target, prop);
}
Next lesson: Proxy use cases