Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading