Created
October 6, 2015 02:42
-
-
Save loklaan/7af8682d343ec5e51072 to your computer and use it in GitHub Desktop.
ES6 Class extending Mixins
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
/** | |
* 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