Hi JavaScripters!
I have been using the mixin pattern a lot. Too bad the syntax for them is still a while away! In the mean time I'm suggesting this new addition to the Reflect Object.
Syntax:
class MyClass extends Reflect.mixin(base, ...composits) { // ...
Traditional mixin:
const mixin1 = {
mix1Prop: 1,
}
const mixin2 = {
mix2Prop: 2,
}
class BaseClass {
baseProp = "I'm a base prop"
baseAction() {
console.log("I'm a base action")
}
}
class MyClass extends BaseClass {
myProp = "It's my prop"
myAction() {}
constructor() {
super()
}
}
Object.assign(MyClass.prototype, mixin1, mixin2)
const myInstance = new MyClass()
myInstance.myProp
myInstance.baseProp
myInstance.mix1Prop
myInstance.mix2Prop
// yay! we got mixins
Here's the new way:
class MyClass extends Reflect.mixin(BaseClass, mixin1, mixin2) {
myProp = "It's my prop"
myAction() {}
constructor() {
super()
}
}
Here's the future:
maximally minimal mixins proposal
class MyClass extends BaseClass with mixin1, mixin2 {
myProp = "It's my prop"
myAction() {}
constructor() {
super()
}
}
Here's how I currently implement it:
const Mixin = (...args) => {
const base = class extends args.splice(0, 1)[0] {}
Object.assign(base.prototype, ...args)
return base
}
// and usage
class MyClass extends Mixin(BaseClass, mixin1, mixin2) { // ...
Honestly mine's not an exact mixin, more like an enriched BaseClass. Therefore it has problems with Object.getPrototypeOf() and others.
Reflect.mixin() may implement it in an alternate / native way.
So there goes the idea. What do you guys think??