JavaScript Reflection

Visualizing the `Reflect` and `Proxy` objects.

Reflect

The `Reflect` object is a built-in object that provides a simple and clean way to perform **metaprogramming** operations. Its methods correspond to the same methods on a `Proxy` handler, giving a standardized approach to calling fundamental JavaScript operations like property access, function invocation, and object extension.

const person = { name: 'Alice' };
Reflect.get(person, 'name'); // 'Alice'

The `Reflect` object is like a standardized API for fundamental object actions. Instead of using syntax (`obj.prop`), you use a method (`Reflect.get(obj, 'prop')`).

{ name: 'John Doe', age: 42 }


Proxy

The `Proxy` object acts as a **placeholder** or a **wrapper** for another object (the `target`). It allows you to intercept and define custom behavior for fundamental operations (like property lookup, assignment, or function calls) on the target object. This interception is managed by a `handler` object that contains "traps" (methods like `get`, `set`, `apply`).

const handler = {
  get: (target, prop) => {
    console.log(`Getting property: ${prop}`);
    return target[prop];
  }
};
const proxy = new Proxy({}, handler);
proxy.a = 1; // Intercepted by 'set' trap
console.log(proxy.a); // Intercepted by 'get' trap

A `Proxy` is like a bouncer for an object. Every request to the object must go through the proxy first, allowing the proxy to inspect, log, or even modify the operation.

Original Object: `user`

Proxy: `userProxy`

All interactions with `userProxy` are logged below.