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

Time:10-30

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.

CodePudding user response:

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;

CodePudding user response:

still trying to figure out what in the world you are trying to accomplish here. you're trying to add a method from one object, to another object?

const blankObject = { hello: data.hello };

though this feels a bit hacky. would probably be best to just pass the whole data object into the constructor, so that the blank object has a reference to it, and can use its methods whenever it needs to.

CodePudding user response:

Doesn't matters, using a test, no needs to over-engineer!

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

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

// We test if the object has a given property and return accordingly 
console.log(

  (blankObject["hello"]) ? blankObject.hello.log() : data.hello.log()

)

  • Related