Last active
June 10, 2020 20:01
-
-
Save Anoesj/8a209eaec6f0c1d98a58f16f32f8d98e to your computer and use it in GitHub Desktop.
JS proxied class definitions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You can safely wrap a class definition in a Proxy. | |
Note that the class instance will not be a Proxy. To do that, this pattern can be used: | |
const handler = {...}; | |
class Foo { | |
constructor () { | |
return new Proxy(this, handler); | |
} | |
} | |
*/ | |
class Foo { | |
constructor () { | |
this.foo = 'foo'; | |
} | |
fooMethod () { | |
console.log(`I'm a method of Foo.`); | |
} | |
} | |
function wrap (classToWrap) { | |
return new Proxy(classToWrap, { | |
get (target, property, receiver) { | |
console.log(`Getting property “${property}” from ${target.prototype.constructor.name}.`); | |
return Reflect.get(...arguments); | |
}, | |
construct (target, args) { | |
console.log(`${target.prototype.constructor.name} constructor called`); | |
return new target(...args); // or Reflect.construct(target, args); | |
}, | |
}); | |
} | |
class Test extends wrap(Foo) { | |
constructor () { | |
super(); | |
console.log(`I extended a class wrapped in a Proxy!`); | |
this.fooMethod(); | |
} | |
} | |
const test = new Test(); | |
console.log(`test instanceof Foo:`, test instanceof Foo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment