你能解释一下为什么这段代码会console.log:
B A
B B
我不太清楚构造函数和 super() 在这种情况下是如何工作的
class A {
constructor(){
this.name = 'A'
this.getName()
}
getName() {
console.log("A " + this.name)
}
}
class B extends A {
constructor(){
super();
this.name = "B";
this.getName()
}
getName(){
console.log("B " + this.name)
}
}
new B
第一个“B A”,因为 super() 调用 A 的构造函数,该构造函数记录“A”,后跟 this.name 的值,即“A”。然后是“B B”,因为 B 的构造函数将 name 设置为“B”并记录“B”,后跟 this.name 的值,即“B”。
TL;DR 要记住的关键一点是,
this
指的是 class B
的 实例,而不是 class A
(即使在调用 super()
时)。因此 this.getName()
将调用 B 类中定义的方法,而 A 类中的方法将被忽略。
按时间顺序思考这段代码很有用。以下是发生的情况的概要:
new B
调用 constructor
中的
B
super()
,调用 constructor
中的
A
this.name = 'A'
将 name
属性设置为 A
this.getName()
中的A
调用getName
中的B
(记住:this
指的是class B
的实例,而不是class A
)。getName
来自 B
输出“B A”(回想一下,this.name
仍然是步骤 4 中的“A”)A
的constructor
完成了,我们回到B
的构造函数this.name = 'B'
将 name
属性设置为 B
this.getName()
从 getName
调用 B
(记住:this
指的是 class B
的实例)getName
来自 B
输出“B B”(回想一下,this.name
是步骤 8 中的“B”)