Search code examples
javascriptecmascript-6es6-proxy

Is it possible to reference a Proxy from its own handler object?


I have a need to reference the current Proxy instance from inside its own handler. I haven't seen this mentioned in any of the documentation I've read and I'm just curious if there's any natural way to do this.

The thing is, inside the handler object, this naturally refers to the handler, not the Proxy it is the handler of.

For example:

var ProxyHandler = {
    get: function(object, property) {
        var thisProxy = ??? // how to reference myProxy from here?
    }
};

var someObj = {foo: "bar"};
var myProxy = new Proxy(someObj, ProxyHandler);

console.log(myProxy.foo);

Solution

  • The signature of a Proxy get handler is

    function(target, property, receiver) {
    

    so since you do myProxy.foo, the receiver argument will be myProxy following the standard logic for property access context.