2

Is there a way to figure out if the property being read of a proxy object is the final property or the intermediate property.

var handler = {
  get(target, key) {
      return new Proxy(target[key], handler) 
  },
  set (target, key, value) {
    target[key] = value;
    return true
  }
}
var proxyObject = new Proxy({}, handler);

Now if I am reading a property proxyObject.a.b.c.d, the get handler would be invoked 4 times, once for each property.
Is there a way for me to figure out when the get is fired for the d property and when the get is fired for some intermediate property like a or b

Ayush Goel
  • 435
  • 6
  • 16
  • 1
    @AyushGoel there are plenty of hacks that make assumptions about how the code is organized and whether or not intermediate references can be stored and accessed later, or if all accesses happen synchronously, etc. but of course these assumptions don't cover all use cases. In general, no this is not possible. – Patrick Roberts Aug 21 '18 at 00:43
  • @PatrickRoberts could you point me to one such hack? It would give me some idea on where to start – Ayush Goel Aug 21 '18 at 00:48
  • Is `d`'s value an object? If not - that is, if it's a primitive - then one *flimsy* method would be to return a Proxy *if* the `target[key]` is an object, and otherwise just return `target[key]`. – CertainPerformance Aug 21 '18 at 00:50
  • @CertainPerformance I'm doing that anyway, cause recursive proxies for primitive objects won't make much sense. I didn't put that in the snippet above to make it simpler. Doing that still won't help me distinguish if a property is intermediate or the final one. – Ayush Goel Aug 21 '18 at 00:52
  • I answered a question like this before... still trying to find a link to it. – Patrick Roberts Aug 21 '18 at 01:02
  • 1
    I can't think of any halfway decent solution either, at least not one that preserves the ability to access what's *actually* behind `.d` while accessing via `proxyObject.a.b.c.d`. You might consider `const dVal = proxyObject.a.b.c.d; console.log(dVal.e)` - what happens then? Pretty sure there's no way to generically identify `d` as the last property before it gets put into `dVal`. You could think about accessing not through proxies, but through a completely separate method, such as `getValue(someObject, ['a', 'b', 'c', 'd'])`. Similar outcome, different accessor syntax. – CertainPerformance Aug 21 '18 at 01:04

0 Answers0