Intermediate level · Module 1: Modern JavaScript Syntax and Modules · Lesson 2 of 3
Classes and Prototypes
Model data and behaviour with classes, getters and private fields, and understand the prototypes underneath.
In this lesson you will
- Write classes with constructors, methods, getters and private fields
- Explain how methods are shared through prototypes
Key concepts
class and constructorgetterprivate field #prototype
The lesson
A class groups data and methods: class Budget { #entries = []; add(entry) { … } get total() { … } }. Fields starting with # are private and cannot be read or changed from outside the class.
Getters look like properties but run code: budget.total calculates the sum each time it is read, so it can never be out of date. Validate inputs in methods and throw errors for invalid data.
Under the hood, JavaScript uses prototypes: methods defined in a class live on its prototype and are shared by all instances. Classes are a clearer way to write the same thing.
Step by step
- Write a Budget class with a private entries array.
- Add add and remove methods with validation.
- Add a total getter.
- Show that two instances share the same add method via the prototype.
Practice activity
Write a ShoppingCart class with private items, add/remove methods and total and itemCount getters.
Expected result: The cart rejects invalid quantities and its getters always reflect the current items.
Check your understanding
-
What does # in front of a field name mean?
Show answer
The field is private to the class.
-
Where are class methods stored?
Show answer
On the class's prototype, shared by all instances.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.