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