Skip to content
Advertisement

How to check and access a function from another object using JavaScript Proxy?

I am practicing JavaScript Proxies and want to access a method from another object but with an empty Proxy object:

const data = {
  hello: {
    log() {
      return 'hello log'
    },
  },
  hi: {
    log() {
      return 'hi log'
    },
  },
}

const blankObject = {} // I can just pass the data object but I want an empty one

const proxy = new Proxy(blankObject, {
  get(target, key) {
    const v = target[key]

    if (typeof v === 'function') {
      // if data.hello.log() or data.hi.log()
      return function() {
         return data[key]['WHAT_TO_DO']// access data.hello.log or data.hi.log() here?
      }
    }

    return v
  }
})

proxy.hello.log() // hello log;

Basically I’m trying to check if that method property exist in another object. I just want to tell the proxy to get the value from another object without passing it into the constructor.

Advertisement

Answer

I don’t understand why you want to use a different object than the object you are proxying. It makes little sense to proxy an empty object instead.

Secondly, if you are going to access the hello property of the proxy object, then realise that this hello value — as found in the data object — is not proxied, so it is not in this proxy that you should check whether the property is a function. At this point the log property is not accessed yet. It’s only about the hello access that the proxy is aware.

But you can divert the path to the data object when hello is accessed, by verifying it is indeed a property of the data object. So:

const data = {
  hello: {
    log() {
      return 'hello log';
    },
  },
  hi: {
    log() {
      return 'hi log'
    },
  },
}

const blankObject = {};

const proxy = new Proxy(blankObject, {
  get(target, key) {
    if (key in data) return data[key]; // <---
    return target[key]; // default
  }
});

console.log(proxy.hello.log()); // hello log;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement