Skip to content

Instantly share code, notes, and snippets.

@CunningFatalist
Created January 26, 2018 07:44
Show Gist options
  • Select an option

  • Save CunningFatalist/0a18ef45ed3bc1347a27ec71940524fc to your computer and use it in GitHub Desktop.

Select an option

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.
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