Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 2
Module 2 · Objects and object-oriented design · Chapter 2 of 28
Cornerstones of OOP in TypeScript: Encapsulation, Abstraction, Inheritance, Polymorphism
No prerequisites. Next up: Object-Oriented Design and UML: Use Case, Class, Sequence, Activity and State Diagrams.
Part 1 · Objects, classes and the prototype chain
What a class is
Most of the code in a design problem is classes, so it helps to know what a class really is. This chapter covers the four ideas behind them and the choice between inheritance and composition.
An object bundles data with the functions that work on that data. A class is a recipe for making objects of one kind: it names the data each object carries (its fields) and the functions they share (its methods). An object made from a class is an instance.
Languages differ in how they build this. JavaScript, and so TypeScript, does not copy methods into every instance. Each object has a hidden link to another object, its prototype, and a method call is looked up along those links. The class keyword is a cleaner way to write down that arrangement. Knowing it explains behaviour that otherwise looks odd, such as why a method is not among an object's own keys.
The prototype chain
Take a Person class and a Student that extends it. Fields such as name and roll are stored on each instance. Methods such as greet are stored once, on Person.prototype. An instance reaches them through its prototype link.