Proxy & Reflect API Deep Dive
Proxy & Reflect API Deep Dive in Modern JavaScript
Introduced in ECMAScript 2015 (ES6), the Proxy and Reflect APIs provide low-level metaprogramming capabilities in JavaScript. While standard objects only allow reading and writing properties, Proxy enables wrapping an object to intercept and redefine 13 fundamental language operations (termed Traps).
1. The 13 Proxy Traps and Their Reflect Equivalents
Every trap in a Proxy handler mirrors a corresponding static method on the built-in Reflect object:
| Proxy Trap | Intercepts | Triggered By | Reflect Method |
|---|---|---|---|
get | Property access | obj.prop, obj['prop'] | Reflect.get() |
set | Property assignment | obj.prop = val | Reflect.set() |
has | The in operator | 'prop' in obj | Reflect.has() |
deleteProperty | Deleting a property | delete obj.prop | Reflect.deleteProperty() |
apply | Function call | fn(...args), fn.apply() | Reflect.apply() |
construct | The new operator | new MyClass() | Reflect.construct() |
getPrototypeOf | Getting prototype | Object.getPrototypeOf() | Reflect.getPrototypeOf() |
setPrototypeOf | Setting prototype | Object.setPrototypeOf() | Reflect.setPrototypeOf() |
isExtensible | Extensibility check | Object.isExtensible() | Reflect.isExtensible() |
preventExtensions | Disabling extensions | Object.preventExtensions() | Reflect.preventExtensions() |
getOwnPropertyDescriptor | Inspecting descriptors | Object.getOwnPropertyDescriptor() | Reflect.getOwnPropertyDescriptor() |
defineProperty | Defining descriptors | Object.defineProperty() | Reflect.defineProperty() |
ownKeys | Enumerating keys | Object.keys(), Object.getOwnPropertyNames() | Reflect.ownKeys() |
2. Why Reflect is Mandatory Inside Proxy Traps
A common beginner mistake is directly calling target[prop] inside a get trap:
The receiver parameter guarantees that if a property is a getter that uses this, this correctly points to the Proxy instance, not the underlying raw target object!
3. Real-World Architectural Implementations
1. Reactive Data Binding (Vue 3 Reactivity Engine)
2. Negative Array Indexing (Python-Style Arrays)
In JavaScript, arr[-1] returns undefined. We can implement Python-style negative indices using Proxy:
4. Revocable Proxies (Proxy.revocable())
A Revocable Proxy creates a proxy that can be completely disconnected and disabled at any time, instantly cutting off access:
Practice Quiz
Metaprogramming in JavaScript
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Crash Reporting & Telemetry Buffering | Metaprogramming in JavaScript |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.