0

Hi, I am trying to transform an object into a proxy, without changing the reference to the object:

Here is a simple class:

class Foo {
  constructor () {
    this.a = 'bar'
  }
}
const foo = new Foo()

Here is my Proxy:

const proxy = new Proxy(foo, {
  get () {
    return 'proxy-bar'
  },
  set () {
    // Don't do anything
    return true
  }
})

Here is what a normal use of this proxy does:

console.log(foo.a) // bar
console.log(proxy.a) // proxy-bar

Now, I want to keep using foo, but with the capabilities of proxy. So I tried to use Object.assign which seems to work only for the getter, but not for the setter. Is their something I miss?

Object.assign(foo, proxy)
console.log(foo.a) // Getter works: proxy-bar

foo.a = 'proxy-proxy-bar'
console.log(foo.a) // Setter does not work: proxy-proxy-bar
Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • "*transform an object into a proxy, without changing the reference to the object*" - that is simply not possible. You need to create `foo` as a proxy in the first place, there's no way around that. – Bergi Dec 01 '19 at 17:08
  • possible duplicate of https://stackoverflow.com/questions/52031628/transform-a-javascript-object-into-a-proxy-and-not-its-reference – Bergi Dec 01 '19 at 17:13

1 Answers1

0

You can apply the proxy in your constructor and return it :

class Foo {
  constructor() {
    this.a = 'bar';
    return new Proxy(this, {
      get() {
        return 'proxy-bar'
      },
      set() {
        // Don't do anything
        return true
      }
    });
  }
}


const foo = new Foo();
foo.a = 'proxy-proxy-bar';
console.log(foo.a); // proxy-bar
Arkerone
  • 1,971
  • 2
  • 22
  • 35