Search code examples
javascriptecmascript-6es6-proxy

Detect whether a Proxy getter is being called from the Proxy or the target


I'm using JavaScript's Proxy object to create a get() handler to trap property access to an instance of a class.

I would like to have different behavior depending on whether the Proxy is being called by methods within the class or by the proxy itself.

Is that possible?

EDIT: Some example code that hopefully explains what I'm trying to do:

class Something {
  constructor() {
    this.prop1 = 'val1';
    this.prop2 = 'val2';
  }

  getProp() {
    return this.prop1;
  }
}

const instance = new Something();

const proxiedObject = new Proxy(instance, {
  get: function(target, property, receiver) {
    if (WHATEVER_IS_ACCESSING_THIS_IS_NOT_AN_INSTANCE_METHOD) {
      return false;
    }
    else {
      return target[property];
    }
  }
});

console.log(proxiedInstance.getProp()); // 'val1'
console.log(proxiedInstance.prop1);     // 'false'

Solution

  • I guess the simplest solution would be to bind all methods when they are accessed on the proxy, so that any accesses to this won't even go through the proxy:

    const proxiedObject = new Proxy(instance, {
      get: function(target, property, receiver) {
        const val = target[property];
        if (typeof val == "function") // you need this anyway for `proxiedObject.getProp()`
          return val.bind(target);
        else
          return false;
      }
    });
    

    Of course there are lots of other ways to wrap the getProp method (or any other methods) so that during its execution the proxy will become transparent for property accesses.