Last active
November 20, 2018 10:17
-
-
Save dualcyclone/fb9f2a2552eae9337ecf3e536b6b9baa to your computer and use it in GitHub Desktop.
Helper to extend a ES6 class from multiple source classes
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
class A = { | |
constructor() { | |
this.A = true | |
} | |
} | |
class B = { | |
constructor() { | |
this.B = true | |
} | |
} | |
class C extends B = { | |
constructor(...args) { | |
super(...args) | |
multiExtend(this, A, args) | |
} | |
} |
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
const multiExtend = (targetInstance, SourceClass, ...args) => { | |
const sourceInstance = new SourceClass(...args) | |
const sourceDescriptors = Reflect.ownKeys(SourceClass) | |
.filter(key => !['constructor', 'name'].includes(key)) | |
.reduce((acc, key) => ([...acc, { key, descriptor: Object.getOwnPropertyDescriptor(SourceClass, key) }]), []) | |
const sourceInstanceDescriptors = Reflect.ownKeys(sourceInstance) | |
.reduce((acc, key) => ([...acc, { key, descriptor: Object.getOwnPropertyDescriptor(sourceInstance, key) }]), []) | |
sourceDescriptors.concat(sourceInstanceDescriptors).forEach(({ key, descriptor }) => { | |
Object.defineProperty(targetInstance, key, descriptor) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment