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

Commit 1f0d716

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

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

pages/Classes.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,10 @@ 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

76-
Derived classes that contain constructor functions must call `super()` which will execute the constructor function on the base class.
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. Derived classes that contain constructor functions must call `super()` which will execute the constructor function on the base class. You have to call `super()` before accessing `this` in the derived constructor. Both `Horse` and `Snake` technically do that since neither one actually references `this`. 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. Neither `Horse` or `Snake`, however, have those kind of properties right now. 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.
7778

7879
The example also shows how to override methods in the base class with methods that are specialized for the subclass.
7980
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)