0
class Base {

    setupServer(){
        console.log("BaseClass")
    }

    listen() {
        this.setupServer();
    }
}

class Child extends Base {

    setupServer() {
        console.log("ChildClass")
    }
}

const child = new Child();
child.listen();

Why does this print out: ChildClass? I would expect this in the Base class to only see the setupServer method in the same class. Is there a way to call the listen function from the child instance and then still execute the Base class setupServer() method first without doing a super.setupServer() in the Child class?

Loupi
  • 550
  • 6
  • 14
  • 5
    That’s how inheritance works. The current object (`this`) only has one method of that name, and in the child that’s the child version. `this` refers to the ***current object***, not the class. – deceze Jul 07 '21 at 17:32
  • 2
    You can invoke Base's setupServer method from Child via `super.setupServer()`, but as @deceze says, the behavior you're seeing is kind of the point of overriding methods. – ray Jul 07 '21 at 17:35
  • Okay that makes sense, but if I remove the `setupServer()` method from the Base class, the compiler complains due to `this.setupServer()` in the listen method. Is this because the compiler does not know that the child class contains the implementation? – Loupi Jul 07 '21 at 17:38
  • @Loupi TS cannot let you do that, because then you will be able to create invalid objects from Base Class itself. – Tushar Shahi Jul 07 '21 at 17:45
  • If you remove it from the base class, then there’s the possibility that you instantiate the base class, and then your code would break. It’s not *type safe* then. – deceze Jul 07 '21 at 17:45

2 Answers2

0

Even when you subclass another class: an instance is just one this object even when a method on the base class gets to do something with it.

So in your example, when the listen method on the Base class invokes this.setupServer(), that this is still child, which is an instance of Child, and the hierarchical lookup of setupServer will therefore match the one defined on Child.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

this in a function depends on how it is executed. Here it is executed on child instance so child's setupServer method will be called.

Regarding the question as to why removing the setupServer from base class shows an error in TS:

class Base {

    listen() {
        this.setupServer();
    }
}

class Child extends Base {

    setupServer() {
        console.log("ChildClass")
    }
}

const child = new Child();
child.listen();

It is simple, in this case you can anytime create an object from Base Class and that will fail when you call this.listen(). Typescript cannot let you do that even if setupServer function is defined later in child class.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39