-
-
Save danleyb2/0f5435fdda129634b9686aa498a3ffb3 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