Created
January 26, 2018 07:44
-
-
Save CunningFatalist/0a18ef45ed3bc1347a27ec71940524fc to your computer and use it in GitHub Desktop.
A nice little pattern for class factories. Can be used to create classes, extend classes, mix in methods... I like it.
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 BaseClass { | |
| constructor(name) { | |
| this.name = name; | |
| this.someFlag = true; | |
| } | |
| } | |
| function factory(name) { | |
| class ExtendedClass extends BaseClass { | |
| constructor() { | |
| super(name); | |
| } | |
| introduce() { | |
| console.log(`I am a ${this.name}`); | |
| } | |
| } | |
| return ExtendedClass; | |
| } | |
| let NiceGuy = factory('Nice Guy'); | |
| let niceGuy = new NiceGuy(); | |
| niceGuy.introduce(); // I am a Nice Guy | |
| console.log(niceGuy.someFlag); // true | |
| let NotSoNiceGuy = factory('Baddy'); | |
| let notSoNiceGuy = new NotSoNiceGuy(); | |
| notSoNiceGuy.introduce(); // I am a Baddy | |
| console.log(niceGuy.someFlag); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment