tc39 / proposal-mixins

A template for ECMAScript proposals
MIT License
61 stars 2 forks source link

Mixin arguments? #11

Open Dragoteryx opened 4 years ago

Dragoteryx commented 4 years ago

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) {
  ...
}
justinfagnani commented 4 years ago

Mixin parameters are definitely useful in some cases, but I didn't include them yet in order to keep the proposal simple. You're right though, there's a pretty simple extension to allow parameters.

richie50 commented 3 years ago

@Dragoteryx Can you explain why the calling super in the context takes some arguments. Sorry i'm just trying to understand

`let MyMixin = (superclass, arg1, arg2) => class extends superclass { constructor(...args) {

why? assuming class T { constructor(){}} , what args are we initializing
super(...args) this.arg1 = arg1; this.arg2 = arg2; } }`

snarbies commented 6 months ago

Taking a cue from decorators, wouldn't it make sense that the accepted value in the mixin position could either be a mixin itself (class Mixed extends Base with MixinValue { }) or a called function that returns a mixin (class Mixed extends Base with MixinFactory(arg1, arg2) { })?