Search code examples
javascriptecmascript-6es6-classes6-proxy

How to wrap object being constructed with Proxy inside constructor?


I understand that Proxy can be used to alter object-level behaviors, such as bracket notation get and set. All the examples I can find show constructing an object and then wrapping it with a Proxy call. Is there a way to define a class Foo, using ES6 class constructor notation, such that the returned object from the constructor is already wrapped in Proxy, rather than the caller of the constructor having to also call Proxy separately?

Thanks in advance.


Solution

  • If I understand your question properly, what you want to do, is in the constructor return a new proxy like this:

    class MyClass {
      constructor() {
        return new Proxy(this, {
          // Proxy settings here
        })
      }
    }
    

    Here in this example, we create a new class, then call a few properties. The proxy will then just print out the properties that were called for simplicity.

    class MyClass {
      constructor() {
        return new Proxy(this, {
          get: (target, key) => {
            console.log('I am the key: ' + key)
            return Reflect.get(target, key)
          }
        })
      }
    }
    
    let c = new MyClass
    c.awesome
    c.billy
    c.superTroopers
    
    if (c instanceof MyClass) {
      console.log('I am an instance of MyClass')
    } else {
      console.log('I am not an instance of MyClass')
    }