proposal-mixins
proposal-mixins copied to clipboard
Mixin arguments?
Why?
The current way of creating mixins allows passing arguments.
let MyMixin = (superclass, arg1, arg2) => class extends superclass {
constructor(...args) {
super(...args)
this.arg1 = arg1;
this.arg2 = arg2;
}
}
class Test {}
class TestMixedIn extends MyMixin(Test, "a", "b) {}
However, this proposal doesn't include that functionnality, which I think is a shame as that would require us to use the old syntax when we want to use mixins with arguments.
It could be written this way:
mixin MyMixin(arg1, arg2) {
constructor(...args) {
super(...args)
this.arg1 = arg1;
this.arg2 = arg2;
}
}
class Test {}
class TestMixedIn extends Test with MyMixin("a", "b) {}
The parenthesis would be optional if the mixin doesn't have any arguments. If the parenthesis are omitted even though the mixin has arguments then they would just be defined as undefined
unless default values are defined. (similar to when using the new
keyword)
mixin MyMixin(arg1 = "a", arg2 = "b") {
constructor(...args) {
super(...args)
this.arg1 = arg1;
this.arg2 = arg2;
}
}
class Test {}
class TestMixedIn extends Test with MyMixin {}
Composition
Extending a mixin that has arguments would look like this:
mixin MyMixin(arg1, arg2) {
...
}
mixin MyCoolerMixin extends MyMixin("a", "b") {
...
}
Which desugars to this:
let MyMixin = (superclass, arg1, arg2) => class extends superclass {
...
}
let MyCoolerMixin = superclass => class extends MyMixin(superclass, "a", "b") {
...
}
Or like this:
mixin MyMixin(arg1, arg2) {
...
}
mixin MyCoolerMixin(arg1, arg2) extends MyMixin(arg1, arg2) {
...
}
Which desugars to this:
let MyMixin = (superclass, arg1, arg2) => class extends superclass {
...
}
let MyCoolerMixin = (superclass, arg1, arg2) => class extends MyMixin(superclass, arg1, arg2) {
...
}