4

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);
devios1
  • 36,899
  • 45
  • 162
  • 260
  • No. You need to save a reference to the proxy. – Aadit M Shah Sep 01 '17 at 21:51
  • (You can reference `myProxy` of course, it's in scope). I do wonder though [what you need this for](https://meta.stackexchange.com/q/66377)? – Bergi Sep 01 '17 at 22:23
  • @Bergi Explaining that would greatly complicate the question and isn't really relevant, but in short, I want to create a recursive chain of proxies for all properties accessed on an object so that I can intercept changes to any sub-property of an object, no matter how deeply nested. I need to be able to reference the parent proxy so it can properly chain together. – devios1 Sep 01 '17 at 22:27
  • @devios1 A reference to the parent `target` object should be enough for that, no? – Bergi Sep 01 '17 at 22:33
  • @Bergi Yes I suppose that would also work… – devios1 Sep 01 '17 at 22:34

2 Answers2

4

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.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • So it is! I don't know how I missed that! I guess the examples I looked at didn't bother to include the third argument, but now that I look at the documentation you are completely right! – devios1 Sep 01 '17 at 22:03
  • 1
    The receiver also could be anything that inherits the property, it might not always be the proxy itself. – Bergi Sep 01 '17 at 22:24
1

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

marvel308
  • 10,288
  • 1
  • 21
  • 32