Last active
June 4, 2023 05:29
-
-
Save cowboy/2619112ea458b4453433360a06b107a8 to your computer and use it in GitHub Desktop.
JavaScript ES6 - mixins with super
This file contains 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
// 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
Why do you consider this a 'mixin' rather than just plain old inheritance?