Skip to content

Instantly share code, notes, and snippets.

@danleyb2
Forked from cowboy/mixin.js
Created April 24, 2019 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danleyb2/0f5435fdda129634b9686aa498a3ffb3 to your computer and use it in GitHub Desktop.
Save danleyb2/0f5435fdda129634b9686aa498a3ffb3 to your computer and use it in GitHub Desktop.
JavaScript ES6 - mixins with super
// This mixin might be used to extend a class with or without its
// own "foo" method
const mixin = Base => class extends Base {
foo() {
// Only call super.foo() if it exists!
if (super.foo) {
super.foo();
}
console.log('mixin');
}
};
class BaseWithMethod {
foo() {
console.log('base with method')
}
}
class myClass1 extends mixin(BaseWithMethod) {}
console.log( (new myClass1).foo() );
// logs:
// base with method
// mixin
class BaseWithNoMethod {}
class myClass2 extends mixin(BaseWithNoMethod) {}
console.log( (new myClass2).foo() );
// logs:
// mixin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment