skip to Main Content

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


  1. 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’.

    Login or Signup to reply.
  2. TL;DR The key thing to remember is that this refers to an instance of class B, not class A (even when calling super()). So this.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:

    1. Both classes are declared with their respective methods.
    2. new B invokes the constructor in B
    3. super() is called, invoking the constructor in A
    4. this.name = 'A' sets the name attribute to "A"
    5. this.getName() in A invokes the getName from B (remember: this refers to an instance of class B, not class A).
    6. getName from B outputs "B A" (recall that this.name is still "A" from step 4)
    7. A‘s constructor is completed, and we return back to B‘s constructor
    8. this.name = 'B' sets the name attribute to "B"
    9. this.getName() invokes the getName from B (remember: this refers to an instance of class B)
    10. getName from B outputs "B B" (recall that this.name is "B" from step 8)
    11. B’s constructor returns, and the program exits
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search