Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active June 4, 2023 05:29
Show Gist options
  • Save cowboy/2619112ea458b4453433360a06b107a8 to your computer and use it in GitHub Desktop.
Save cowboy/2619112ea458b4453433360a06b107a8 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
@leegee
Copy link

leegee commented Sep 18, 2019

Why do you consider this a 'mixin' rather than just plain old inheritance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment