Skip to main content

Welcome to a Grasp lesson

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

Lesson 27

Intercepting Function Calls and Constructor Behavior with Proxies

This lesson is built with resources from stackoverflow.com and exploringjs.com.

Hello! Welcome back to our journey into advanced JavaScript.

In the previous lesson, we explored how to use get and set traps to create self-validating objects, enforcing data integrity at a fundamental level. We saw how intercepting these basic operations with a Proxy can build a robust defensive layer around your data.

Today, we move from intercepting property access to intercepting actions: function calls and constructor invocations. Your learning goal is to use the apply trap to intercept function calls and the construct trap for new operator behavior. These traps are only available when the proxy's target is a function, opening up powerful ways to control and augment how functions and classes are executed.

1. The apply Trap: Intercepting Function Calls

The apply trap is your gateway to intercepting any call made to a function that has been wrapped in a proxy. This includes direct calls proxy(), as well as calls via proxy.call() and proxy.apply().

Let's start by defining what this trap does.

Metaprogramming with Proxies β€’ Deep JavaScript

The "Deep JavaScript" book by Dr. Axel Rauschmayer provides a concise reference for all proxy traps. Let's look at its definition of the function-specific traps.

In the "Reference: the Proxy API" section, find the subsection "Traps for functions". Note the operations intercepted by apply and construct.

As the resource shows, the apply trap's signature is apply(target, thisArgument, argumentsList).

  • target: The original function being proxied.
  • thisArgument: The value of this for the call.
  • argumentsList: An array of arguments passed to the function.

As we established in the last lesson, the best practice for forwarding an intercepted operation is to use the Reflect API. For the apply trap, we use Reflect.apply.

// The target function
function sum(a, b) {
  return a + b;
}

const handler = {
  apply(target, thisArg, argumentsList) {
    console.log(`Calling '${target.name}' with arguments: ${argumentsList}`);
    
    // Forward the call to the original function
    const result = Reflect.apply(target, thisArg, argumentsList);
    
    console.log(`'${target.name}' returned: ${result}`);
    return result;
  }
};

const pSum = new Proxy(sum, handler);

// Now, let's call the proxy
pSum(5, 10);
// LOG: Calling 'sum' with arguments: 5,10
// LOG: 'sum' returned: 15

This pattern is incredibly useful for logging, performance monitoring, or adding pre- and post-processing steps to a function without modifying its original source code.


2. The construct Trap: Intercepting new

When a function can be used as a constructor (like a class), the construct trap allows you to intercept its instantiation via the new keyword.

The construct trap's signature is construct(target, argumentsList, newTarget).

  • target: The original constructor (the class).
  • argumentsList: The array of arguments passed to the constructor.
  • newTarget: The constructor that was actually called. In our case, this will be the proxy itself.

The corresponding Reflect method is Reflect.construct. Its signature is Reflect.construct(target, argumentsList, newTarget). Passing the newTarget parameter is important for correctly setting up the prototype chain, especially in inheritance scenarios.

Let's see it in action with a simple class.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const constructorHandler = {
  construct(target, args, newTarget) {
    console.log(`Instantiating '${target.name}'...`);
    
    // Forward the instantiation to the original constructor
    const instance = Reflect.construct(target, args, newTarget);
    
    console.log(`Created instance of '${target.name}' with name: ${instance.name}`);
    return instance;
  }
};

const ProxiedPerson = new Proxy(Person, constructorHandler);

const p = new ProxiedPerson('Alice', 30);
// LOG: Instantiating 'Person'...
// LOG: Created instance of 'Person' with name: Alice

This gives you control over the object creation process, allowing for instance counting, validation of constructor arguments, or even returning a completely different object.

Test your understanding!

Imagine you have a function that can be both called directly and used as a constructor.

function User(name) {
  if (new.target) {
    // Called with 'new'
    this.name = name;
    this.role = 'user';
  } else {
    // Called directly
    return `Guest user: ${name}`;
  }
}

Create a single proxy handler that uses both apply and construct traps to log whether User was called as a regular function or as a constructor.

Show answer
function User(name) {
  if (new.target) {
    this.name = name;
    this.role = 'user';
  } else {
    return `Guest user: ${name}`;
  }
}

const userHandler = {
  apply(target, thisArg, args) {
    console.log('User was called as a function.');
    return Reflect.apply(target, thisArg, args);
  },
  construct(target, args, newTarget) {
    console.log('User was called as a constructor.');
    return Reflect.construct(target, args, newTarget);
  }
};

const ProxiedUser = new Proxy(User, userHandler);

// Test the 'apply' trap
const greeting = ProxiedUser('Bob'); // Logs: "User was called as a function."
console.log(greeting); // "Guest user: Bob"

// Test the 'construct' trap
const userInstance = new ProxiedUser('Charlie'); // Logs: "User was called as a constructor."
console.log(userInstance); // User { name: 'Charlie', role: 'user' }

3. The Challenge: Intercepting Instance Method Calls

We've successfully proxied a standalone function and a constructor. But what happens when we want to intercept method calls on an instance created by our proxied constructor? This is a common requirement and a frequent point of confusion.

Let's examine a scenario where this becomes tricky.

mixing constructor and apply traps on the Javascript Proxy ...

This Stack Overflow question perfectly frames the problem. A developer wants to use a single proxy to log both the constructor call and the subsequent method calls on the created instance, but the apply trap isn't firing for the methods. Let's analyze why.

Read the question body, including the Calculator.js and index.js code. Understand the developer's goal and their (incorrect) assumption about how the apply trap would work here.

The reason the apply trap on LoggedCalculator doesn't fire for calculator.add() is that the proxy is wrapped around the Calculator class, not the calculator instance. The call calculator.add(1,2) is a sequence of operations on the calculator object, which is a plain, un-proxied object. The JS engine performs:

  1. A [[Get]] operation on calculator to retrieve the add method.
  2. An [[Apply]] operation on the retrieved method.

Our proxy is not involved in either of these steps.

The solution is elegant and showcases the composability of proxies: we need a proxy that creates other proxies.

mixing constructor and apply traps on the Javascript Proxy ...

The highest-voted answer on the same Stack Overflow page provides a robust solution using nested proxies. This is a key pattern in metaprogramming.

Read the second answer (by user 'uber5001'). Pay close attention to the structure: the construct trap of the outer proxy returns a new proxy that wraps the instance. This inner proxy uses a get trap to intercept method access.

Let's break down this powerful pattern:

  1. Outer Proxy (Class Proxy): Its primary job is to intercept the new call using the construct trap.
  2. construct Trap Logic:
    • It first creates the genuine instance using Reflect.construct.
    • Instead of returning this instance directly, it wraps it in a new, inner proxy.
    • It then returns this inner proxy.
  3. Inner Proxy (Instance Proxy): This proxy is wrapped around the actual object instance. Its job is to intercept operations on the instance, such as method calls.
  4. get Trap Logic (Inner Proxy): To intercept a method call like instance.add(), we must first intercept the access to the add property.
    • The get trap fires when instance.add is accessed.
    • Inside the trap, we check if the requested property is a function.
    • If it is, we don't return the original function. Instead, we return a new wrapper function.
    • This wrapper function, when finally called, can execute our logging/interception logic and then use Reflect.apply to call the original method with the correct this context and arguments.

Here is the pattern synthesized into a reusable factory function:

function createTracedClass(TargetClass) {
  const classHandler = {
    construct(target, args, newTarget) {
      console.log(`[CONSTRUCT] Creating instance of ${TargetClass.name}`);
      
      // 1. Create the real instance
      const instance = Reflect.construct(target, args, newTarget);
      
      // 2. Wrap the instance in an inner proxy
      const instanceHandler = {
        get(instTarget, prop, receiver) {
          const value = Reflect.get(instTarget, prop, receiver);

          // 3. If property is a function, return a wrapper
          if (typeof value === 'function') {
            return function(...callArgs) {
              console.log(`[CALL] Calling method '${prop}' with args: ${callArgs}`);
              // 4. Execute the original function
              return Reflect.apply(value, instTarget, callArgs);
            }
          }
          return value;
        }
      };
      
      return new Proxy(instance, instanceHandler);
    }
  };
  
  return new Proxy(TargetClass, classHandler);
}

// ---- Usage ----
class Calculator {
  add(a, b) { return a + b; }
  subtract(a, b) { return a - b; }
}

const TracedCalculator = createTracedClass(Calculator);

const calc = new TracedCalculator(); 
// LOG: [CONSTRUCT] Creating instance of Calculator

const sum = calc.add(10, 5); 
// LOG: [CALL] Calling method 'add' with args: 10,5
console.log(sum); // 15

This pattern effectively combines the construct, get, and apply concepts to achieve comprehensive tracing of both instantiation and method invocation.


Conclusion

You have now extended your metaprogramming skills from object properties to object behaviors. By mastering the apply and construct traps, you can intercept and augment the very actions of functions and classes.

Key Takeaways:

  • The apply trap intercepts function calls, receiving the target function, this value, and arguments list.
  • The construct trap intercepts new operations, receiving the target constructor, arguments list, and the new.target value.
  • Both traps should use their Reflect API counterparts (Reflect.apply, Reflect.construct) for correct and robust forwarding of the original operation.
  • To intercept method calls on a proxied class's instance, you must use a nested proxy pattern: the construct trap returns a new proxy for the instance, which in turn uses a get trap to wrap methods in functions that perform the desired interception logic.

Next Up

Throughout these lessons, we've consistently used methods like Reflect.get, Reflect.set, Reflect.apply, and Reflect.construct as a best practice for forwarding operations from within proxy traps. In our next lesson, we will formalize this by taking a comprehensive look at the Reflect API. You will learn how its methods provide a complete, one-to-one mapping to the proxy traps and why it is the superior mechanism for metaprogramming operations.