Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 28

Default Forwarding with Reflect API

This lesson is built with resources from youtube.com, dev.to and 1 more site.

Hello! Welcome back to our deep dive into JavaScript's metaprogramming capabilities.

In our last lesson, we saw how to intercept function calls and constructor invocations using the apply and construct traps. We noted that using Reflect.apply and Reflect.construct was the best practice for forwarding those operations. Today, we're going to formalize that idea and explore why the Reflect API is not just a convenient helper, but an essential partner to Proxy for creating robust and correct metaprogramming logic.

Your learning goal for this lesson is to utilize the Reflect API methods as the default forwarding behavior within proxy traps. We'll uncover subtle bugs that arise from "naive" forwarding and see how Reflect is specifically designed to solve them.

1. The Pitfall of Naive Forwarding

When you're first learning proxies, it's tempting to implement a simple "pass-through" trap like this:

const handler = {
  get(target, prop) {
    console.log(`Getting property: ${prop}`);
    return target[prop]; // Naive forwarding
  },
  set(target, prop, value) {
    console.log(`Setting property: ${prop}`);
    target[prop] = value; // Naive forwarding
    return true;
  }
};

This seems logical, and for simple objects, it works. However, this approach has a critical flaw related to the this context, especially when dealing with prototype chains and getters.

Let's explore a scenario where this breaks down.

Why We Use Reflect for Proxy Handlers

The article "Why We Use Reflect for Proxy Handlers" by Daishi Kato presents a perfect, concise example of this problem. Please read the first part to see how a naive proxy fails in a non-obvious way.

Read the section titled "Understanding the Edge Case". Focus on why the code console.log(derived.doubled) outputs 2 instead of the expected 4.

As the article demonstrates, the issue lies in how the this context is resolved. When the doubled getter is accessed via the derived object, the get trap on the proxy is triggered. However, the line return target[prop] executes the getter in the context of target (the base object), not the object that initiated the call (derived). Therefore, this.count inside the getter resolves to base.count, which is 1, leading to the incorrect result.


2. The Solution: Reflect and the receiver

This is precisely the problem that the Reflect API is designed to solve. Proxy traps like get and set receive a third argument called receiver.

  • receiver: The object on which the property access was originally performed. In our example, this is the derived object.

The Reflect methods are designed to accept this receiver and use it to preserve the correct this context.

Let's see the solution in action.

Why We Use Reflect for Proxy Handlers

Now, let's examine the fix provided in the same article.

Read the sections "The Solution: Using Reflect.get" and "Why Reflect.get Works". Observe how passing the receiver argument to Reflect.get solves the this context problem.

By changing return target[prop] to return Reflect.get(target, prop, receiver), we are telling the JavaScript engine: "Get this property from the target, but if it's a getter, make sure its this context is set to the receiver." This ensures the behavior is identical to a direct property access on the derived object, preserving the integrity of the prototype chain.

This leads to a fundamental rule of thumb for proxies:

Always use the corresponding Reflect method for default forwarding inside a proxy trap.


3. A Complete Partnership: Proxy Traps and Reflect Methods

The relationship between Proxy and Reflect is not accidental. They were designed together as part of the ES6 specification to form a complete meta-object protocol (MOP). For every trap available in a Proxy handler, there is a corresponding static method on the Reflect object with a matching signature.

Here is a table of the most common pairings:

Proxy Trap Reflect Method Description
get(target, prop, receiver) Reflect.get(target, prop, receiver) For reading a property's value.
set(target, prop, value, receiver) Reflect.set(target, prop, value, receiver) For setting a property's value.
has(target, prop) Reflect.has(target, prop) For the in operator.
apply(target, thisArg, args) Reflect.apply(target, thisArg, args) For calling a function.
construct(target, args, newTarget) Reflect.construct(target, args, newTarget) For the new operator.
deleteProperty(target, prop) Reflect.deleteProperty(target, prop) For the delete operator.
defineProperty(target, prop, desc) Reflect.defineProperty(target, prop, desc) For Object.defineProperty.

This one-to-one mapping makes writing robust handlers straightforward. Your logic becomes:

  1. Perform any custom interception logic (logging, validation, etc.).
  2. Forward the operation using the corresponding Reflect method, passing along all the arguments you received.
  3. Perform any post-operation logic if needed.

4. More Practical Failures of Naive Forwarding

The getter/prototype example is subtle. Let's look at more common built-in objects where naive forwarding fails spectacularly. Consider proxying a Map.

const map = new Map([['a', 1]]);
const naiveProxyMap = new Proxy(map, {
  get(target, prop) {
    return target[prop]; // This is the problem
  }
});

// This will throw an error!
// naiveProxyMap.get('a');
// Uncaught TypeError: Method Map.prototype.get called on incompatible receiver

When you call naiveProxyMap.get('a'), the JavaScript runtime first tries to get the get method from the proxy. Our trap intercepts this and returns target['get'], which is the original Map.prototype.get function. Then, the runtime tries to call this function. The internal implementation of Map.prototype.get checks that its this value is a genuine Map instance. However, since the call is naiveProxyMap.get(...), the this value is the proxy object, not the original map, causing the TypeError.

The Reflect API, combined with a bit of context-binding, provides the correct solution.

Combine Proxy traps with the Reflect API

The article "Combine Proxy traps with the Reflect API" explores this Map issue and another one involving private class fields, then presents a universal handler that solves them using Reflect.

First, read the sections "Creating a Proxy for a Map object" and "Proxy a class with private fields" to understand two more scenarios where naive proxies fail. Then, study the solution in the section "Using Reflect with Proxy", paying close attention to the implementation of the get and set handlers.

The handler proposed in the article is a great example of a robust, general-purpose forwarding mechanism:

const handler = {
  get(target, property, receiver) {
    // Forward the operation, but ensure 'this' is correct for methods
    const value = Reflect.get(target, property, receiver);
    if (typeof value === 'function') {
      return value.bind(target);
    }
    return value;
  },
  set(target, property, value, receiver) {
    // Simple forwarding is enough here
    return Reflect.set(target, property, value, receiver);
  },
};

const map = new Map([['a', 1]]);
const correctProxyMap = new Proxy(map, handler);

console.log(correctProxyMap.get('a')); // Works! Outputs: 1

correctProxyMap.set('b', 2); // Works!
console.log(correctProxyMap.get('b')); // 2

The key is in the get trap. Reflect.get correctly retrieves the property or method. Then, the check typeof value === 'function' identifies methods. value.bind(target) returns a new function that is permanently bound to the original target (the Map instance). When this bound function is later called, its this context is guaranteed to be the original map, satisfying the internal check and preventing the TypeError.

This pattern elegantly solves the issues with both Map methods and the private field access shown in the article.

Test your understanding!

You have a Secretive class that uses a private field.

class Secretive {
  #secret = "42";

  reveal() {
    return this.#secret;
  }
}

Create a proxy for an instance of Secretive. The proxy's handler should:

  1. Log to the console every time a property is accessed (using a get trap).
  2. Ensure that calling proxy.reveal() works correctly and doesn't throw a TypeError.

Use Reflect.get in your implementation.

Show answer
class Secretive {
  #secret = "42";

  reveal() {
    return this.#secret;
  }
}

const instance = new Secretive();

const handler = {
  get(target, prop, receiver) {
    console.log(`Accessing property: "${prop}"`);

    // We must use Reflect.get to ensure methods like `reveal`
    // are called with the correct 'this' context (the original instance),
    // which allows them to access private fields.
    const value = Reflect.get(target, prop, receiver);

    // For methods on built-ins, binding might be needed, but for
    // regular class methods, Reflect.get with the receiver is often sufficient.
    // To be fully robust, we can add the bind.
    if (typeof value === 'function') {
        return value.bind(target);
    }

    return value;
  }
};

const proxy = new Proxy(instance, handler);

// This call will now work correctly.
const revealed = proxy.reveal(); 
// LOG: Accessing property: "reveal"

console.log(revealed); // "42"

The key is that Reflect.get (or the subsequent .bind(target)) ensures that when reveal is executed, its this refers to the original instance, which is the only object that has access to the #secret private field. A naive target[prop] would cause this to be the proxy, leading to an error.


Conclusion

Today, you've solidified a crucial principle of JavaScript metaprogramming: Proxy and Reflect are inseparable partners. Using them together is the key to building proxies that are not only powerful but also correct and robust.

Key Takeaways:

  • Naive forwarding of operations (e.g., return target[prop]) is brittle and can lead to subtle bugs related to this context, especially with getters, prototypes, and methods on built-in objects.
  • The Reflect API provides a complete set of static methods that mirror the Proxy traps, designed specifically for forwarding operations.
  • Using Reflect methods within traps (e.g., Reflect.get(target, prop, receiver)) correctly preserves the this context via the receiver argument, ensuring that proxied objects behave identically to their originals.
  • This Proxy+Reflect pattern is the standard and most reliable way to implement default behavior in your proxy handlers.

Next Up

Now that you have a firm grasp on how to build robust proxies that correctly forward operations, we'll put this knowledge to practical use. In the next lesson, we will build an observable object that notifies subscribers of property changes using a set trap. This is a foundational pattern used in many modern frontend frameworks and state management libraries.