Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Last active March 29, 2024 06:03
Show Gist options
  • Star 96 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save sebmarkbage/fac0830dbb13ccbff596 to your computer and use it in GitHub Desktop.
Save sebmarkbage/fac0830dbb13ccbff596 to your computer and use it in GitHub Desktop.
Mixin
var Bar1 = base => class extends base {
componentWillMount(){
super.componentWillMount();
console.log('Bar1');
}
};
var Bar2 = base => class extends base {
componentWillMount(){
super.componentWillMount();
console.log('Bar2');
}
};
class Foo extends mixins(Bar1, Bar2) {
componentWillMount() {
console.log('Foo before mixins');
super.componentWillMount();
console.log('Foo after mixins');
}
}
function mixins(...mixinFactories) {
var base = class {};
// TODO: Add all possible method names that might call super()
// to the base class so that they don't throw.
for (var i = 0; i < mixinFactories.length; i++) {
base = mixinFactories[i](base);
}
return base;
}
@nhansum
Copy link

nhansum commented Jan 15, 2018

Hey, great gist I encountered a problem though when trying it out:

Bar1 should have super.componentWillMount(); removed otherwise it will result in a TypeError

@jeel2308
Copy link

Great Example

@nuts-n-bits
Copy link

lol never knew the spec was like this. IDK if I should be impressed or dreaded!

@pmvald
Copy link

pmvald commented Aug 29, 2021

This is abusing the language capabilities. Mixin and inheritance are two different concepts with two different goals. For mixin, the support either should come from the language or you can just create instances of the mixin classes inside the host class and proxy to their methods.

@divanshArora
Copy link

@pmvald Could you elaborate on "create instances of the mixin classes inside the host class and proxy to their methods" please. I am trying to do that

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