Ming
Ming

Reputation: 1693

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.

Upvotes: 4

Views: 2512

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

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')
}

Upvotes: 4

James Long
James Long

Reputation: 4736

As far as I know: no, but you can set the prototype afterwards. Something like this:

class Thing {

    constructor() {
        // ...
    }

}

Thing.prototype = new Proxy(Thing.prototype, {

    get(target, name) {
        // ...
    }

});

Upvotes: -1

Related Questions