Could you explain why this code will console.log:
B A
B B
I don’t exactly know how constructors and super() work in this case
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
2
Answers
First "B A" because super() invokes the constructor of A, which logs "A" followed by the value of this.name, which is ‘A’. Then "B B" because the constructor of B sets name to ‘B’ and logs "B" followed by the value of this.name, which is ‘B’.
TL;DR The key thing to remember is that
this
refers to an instance ofclass B
, notclass A
(even when callingsuper()
). Sothis.getName()
will invoke the method defined in class B, and the method from class A is ignored.It’s useful to think about this code in chronological order. Here’s the rundown on what happens:
new B
invokes theconstructor
inB
super()
is called, invoking theconstructor
inA
this.name = 'A'
sets thename
attribute to "A"this.getName()
inA
invokes thegetName
fromB
(remember:this
refers to an instance ofclass B
, notclass A
).getName
fromB
outputs "B A" (recall thatthis.name
is still "A" from step 4)A
‘sconstructor
is completed, and we return back toB
‘s constructorthis.name = 'B'
sets thename
attribute to "B"this.getName()
invokes thegetName
fromB
(remember:this
refers to an instance ofclass B
)getName
fromB
outputs "B B" (recall thatthis.name
is "B" from step 8)