Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

Commit 89a00ed

Browse files
committed
Explain constructor rules better in Classes.md
1 parent e0e0be5 commit 89a00ed

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

pages/Classes.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,16 @@ tom.move(34);
7171
```
7272

7373
This example covers quite a few of the inheritance features in TypeScript that are common to other languages.
74+
7475
Here we see the `extends` keywords used to create a subclass. You can see this where `Horse` and `Snake` subclass the base class `Animal` and gain access to its features.
7576

77+
TypeScript has some restrictions about constructors intended to help ensure instances of a class have their properties correctly initialized before the properties are used.
7678
Derived classes that contain constructor functions must call `super()` which will execute the constructor function on the base class.
79+
You have to call `super()` before accessing `this` in the derived constructor.
80+
Both `Horse` and `Snake` technically do that since neither one actually references `this`.
81+
A `super()` call must also be the first statement in the constructor of a derived class when the derived class contains initialized properties or has parameter properties.
82+
Neither `Horse` or `Snake`, however, have those kind of properties right now.
83+
So, as long as those two classes stay that way, they could have console logging or other statements before the `super()` call in their constructors without generating compile-time errors.
7784

7885
The example also shows how to override methods in the base class with methods that are specialized for the subclass.
7986
Here both `Snake` and `Horse` create a `move` method that overrides the `move` from `Animal`, giving it functionality specific to each class.

0 commit comments

Comments
 (0)