Created
January 4, 2019 02:14
-
-
Save krisselden/dc9bac9c5d1994e927a19e7023ede6b6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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