Skip to content

Instantly share code, notes, and snippets.

@krisselden
Created January 4, 2019 02:14
Show Gist options
  • Save krisselden/dc9bac9c5d1994e927a19e7023ede6b6 to your computer and use it in GitHub Desktop.
Save krisselden/dc9bac9c5d1994e927a19e7023ede6b6 to your computer and use it in GitHub Desktop.
function bound() {
return (target, key, descriptor) => {
const symbol = Symbol(key);
const { enumerable, configurable, value } = descriptor;
return {
enumerable,
configurable,
get() {
let fn = this[symbol];
if (fn === undefined) {
this[symbol] = fn = value.bind(this);
}
return fn;
}
}
}
}
function applyDecorator(target, key, decorator) {
let descriptor = Object.getOwnPropertyDescriptor(target, key);
Object.defineProperty(target, key, decorator()(target, key, descriptor));
}
class A {
perform(x) {
console.log(`A.perform(${x})`);
}
}
applyDecorator(A.prototype, 'perform', bound);
class B extends A {
perform(x) {
super.perform(x);
console.log('B.perform');
}
}
applyDecorator(B.prototype, 'perform', bound);
const a = new A();
const b = new B();
const { perform: aPerform } = a;
const { perform: bPerform } = b;
aPerform(19);
bPerform(23);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment