Skip to content

Alternatives in the example code of 1-js/09-classes/07-mixins may be wrong #2461

@AmosChenYQ

Description

@AmosChenYQ
let sayMixin = {
  say(phrase) {
    alert(phrase);
  }
};

let sayHiMixin = {
  __proto__: sayMixin, // (or we could use Object.create to set the prototype here) !!! this may be wrong

  sayHi() {
    // call parent method
    super.say(`Hello ${this.name}`); // (*)
  },
  sayBye() {
    super.say(`Bye ${this.name}`); // (*)
  }
};

class User {
  constructor(name) {
    this.name = name;
  }
}

// copy the methods
Object.assign(User.prototype, sayHiMixin);

// now User can say hi
new User("Dude").sayHi(); // Hello Dude!

Object.create can set proto of sayHiMixin, but its method can be only function properties by

let sayHiMixin = Object.create(sayMixin, {
    sayHi: {
        value: function() {
            super.say(`Hello ${this.name}`);
        },
        enumerable: true
    }
});

or

sayHiMixin.sayHi = function() {
 // ....
}

Calling super later will cause an error becasue both in these way there;s no [[HomeObject]], super keyword unexpected here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions