ๅจๅๅงๅ็้็จไธญ๏ผๅ ็บ parent class ็ class fields ๆๅ
ๅๅงๅใconstructor ๆๅ
ๅท่ก๏ผๆไปฅๅฆๆๆญคๆๅจ parent constructor ๅ
งๆๅ this ็ฉไปถ็ overridden class fields ็่ฉฑ๏ผ็ฑๆผ้ๆ็ overridden class fields ๅฐๆชๅฎๅ
จๅๅงๅ๏ผๅ ๆญคๅฏ่ฝๆ็ข็ใ่ผธๅบ้ฏ่ชค(ๆชๆ็)็ๅฑฌๆงใ็ๅ้กโ๏ธ
๐ ่ฉณๆ
่ซ็๏ผ override class fieldsใโ็ๆณ ใ้ ้ข
โญ๏ธ Note: when "parent constructor" is called (in an initialization process):
"overridden methods" are used โ
"parent class fields" are used โโ
ไนๅฐฑๆฏ่ชช๏ผๅฆๆๅจ parent constructor ๆๅผๅซ overridden methods๏ผๅ overridden methods ๆ่ขซๅท่ก๏ผไฝๆญคๆๆๆๅ็ไปปไฝ this ็ฉไปถๅฑฌๆง้ฝ้ๆๆฏ็จ parent class fields๏ผๅ ็บๅจ้ๅๆ้้ป๏ผoverride class fields ้ๆฒๆๆฉๆๅๅงๅโ
const { log } = console;
class A {
// ๐ F1: class field
name = 'A'
// โญ C1: base constructor
// ----------------------------------------
// when "parent constructor" is called:
// 1. "overridden methods" are used โ
// 2. "parent class fields" are used โโ
// ----------------------------------------
constructor() {
this.showName(); // โญ 1. "overridden method" is used โ
}
// ๐ธ M1: method
showName() {
// โญ 2. "parent class fields" are used โโ
log(`A: name = ${this.name}`);
}
}
class B extends A {
// ๐ F2: override class field
name = "B"
// โญ C2: override constructor
constructor() {
super();
this.showName(); // โญ "overridden method" is usedโโโ
}
// ๐ธ M2: override method
showName() { log(`B: name = ${this.name}`); }
}
class C extends B {
// ๐ F3: override class field
name = "C"
// โญ C3: override constructor
constructor() {
super();
this.showName();
}
// ๐ธ M3: override method
showName() { log(`C: name = ${this.name}`); }
}
new A(); // "A: name = A"
new B(); // "B: name = A", "B: name = B"
new C(); // "C: name = A", "C: name = B", "C: name = C"
// -----------------------------------------
// process this console
// -----------------------------------------
// ๐ F1: name = 'A' โฎ
// โญ C1: โ new A()
// ๐ธ M1: "A: name = A" โฏ
// -----------------------------------------
// ๐ F1: name = 'A' โฎ
// โญ C1: โ
// โ M2: "B: name = A" โ
// ๐ F2: name = 'B' โ new B()
// โญ C2: โ
// ๐ธ M2: "B: name = B" โฏ
// -----------------------------------------
// ๐ F1: name = 'A' โฎ
// โญ C1: โ
// โ M3: "C: name = A" โ
// ๐ F2: name = 'B' โ
// โญ C2: โ new C()
// โ M3: "C: name = B" โ
// ๐ F3: name = 'C' โ
// โญ C3: โ
// ๐ธ M3: "C: name = C" โฏ
// -----------------------------------------