Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
AmosChenYQ opened this issue Jan 23, 2021 · 1 comment
Closed

Comments

@AmosChenYQ
Copy link
Contributor

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.

@iliakan
Copy link
Member

iliakan commented Jan 23, 2021

Indeed. Merged!

@iliakan iliakan closed this as completed Jan 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants