Blog>
Snippets

Manipulating 'this' Context in Method Calls with Proxies

Use a Proxy to intercept method calls and manipulate the 'this' context before passing control to the original function.
// Create an object with a method that uses 'this'
const originalObject = {
  value: 42,
  getValue() {
    return this.value;
  }
};

// Define a custom 'this' context that we want to inject
const customThisContext = { value: 100 };

// Create a proxy to intercept method calls
const proxiedObject = new Proxy(originalObject, {
  get(target, prop, receiver) {
    // Intercept method access
    if (typeof target[prop] === 'function') {
      // Return a bound function with the custom 'this' context
      return function(...args) {
        return target[prop].apply(customThisContext, args);
      };
    }
    // For non-function properties, just return the original property
    return Reflect.get(target, prop, receiver);
  }
});

// Test the behavior
console.log(originalObject.getValue()); // Should log 42
console.log(proxiedObject.getValue());  // Should log 100
This code defines an object with a method that uses 'this', and then creates a proxy to intercept method calls. When a method is accessed, the proxy binds the method to a custom 'this' context before executing it. As a result, when we call the proxied method, it uses the value from the custom 'this' context instead of the original object's value.