Skip to content

Instantly share code, notes, and snippets.

@loklaan
Created October 6, 2015 02:42
Show Gist options
  • Save loklaan/7af8682d343ec5e51072 to your computer and use it in GitHub Desktop.
Save loklaan/7af8682d343ec5e51072 to your computer and use it in GitHub Desktop.
ES6 Class extending Mixins
/**
* An implementation for composing classes together.
*
* The composition part looks like below, using the mixin function:
*
* class ComposedClass extends mixin(ParentClass, ...classGenerators) {
* render() {
* // Note: To call something from renderTextMixin, use super
* super.render()
* this.renderText('Hello world');
* }
* }
*
* The class generators are functions that return classes extending on the parent
* class. They should follow the following pattern:
*
* function renderTextMixin(parentClass) {
* return class extends parentClass {
* render() {
* // We're calling the parents classes .render() function.
* // If we wanted to overwrite .render(), simply don't call super.render()
* super.render && super.render()
* console.log('renderTextMixin enabled')
* }
*
* // Attaches the renderText() to the class, to use elsewhere
* renderText(text) {
* console.log(text)
* }
* }
* }
*
* Original Credit: https://gist.github.com/aldendaniels/5d94ecdbff89295f4cd6
*/
export default function mixin(ParentClass, ...classGenerators) {
return classGenerators.reduce((ParentClass, classGenerator) => {
return classGenerator(ParentClass);
}, ParentClass);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment