mixin inheritance
replit ⟩ mixin inheritance
const { log } = console;
// -------------- Mixin Inheritance --------------
// ⭐ mixin's base object
const canSaySomething = {
say(phrase) { log(phrase) }
};
// ⭐ inherits from `canSaySomething`
const canSayHi = {
// -------------------------------------
// ⭐ prototype chain:
// can use Object.setPrototypeOf() instead.
__proto__: canSaySomething,
// -------------------------------------
// -------------------------------------
// ⭐ super
// === [[HomeObject]].[[Prototype]]
// === canSayHi.[[Prototype]]
// === canSaySomething
// -------------------------------------
sayHi() { super.say(`Hello ${this.name}!`) },
sayBye() { super.say(`Bye ${this.name}!`) },
};
// User
class User {
constructor(name) {
this.name = name;
}
}
// --------------- mix in --------------------------
// ⭐ copy all enumerable own members from mixin(s)
// to `User.prototype` (NOT `User`).
//
// ╭ ⭐️ target ╮ ╭source─╮
Object.assign( User.prototype, canSayHi );
const dude = new User("Dude");
dude.sayHi(); // Hello Dude!
dude.sayBye(); // Bye Dude!
// ------------------- 🧨 雷區 ----------------------------
// ⭐ 注意:
// 不能呼叫 mixin's base object 中的 methods❗
// 如果 dude 找不到 say(),它會往自己的 prototype chain 找,
// 而不是在 mixin 的 prototype chain 找,要特別注意❗
// -------------------------------------------------------
// ⛔ TypeError: `dude.say` is not a function
dude.say(`I'm super!`);
super is used to refer to mixin's parent object.
mixin's methods know their [[HomeObject]].
Last updated