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

887 views Asked by At

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);
2

There are 2 answers

2
loganfsmyth On BEST ANSWER

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.

0
marvel308 On

The default behaviour of handler is as follows

let handler = {
    get(target, propKey, receiver) {
        return (...args) => console.log(args);
    }
};
let proxy = new Proxy({}, handler);

the receiver is of type Proxy and in our case it is the object myProxy