JavaScript OOP: Classes & Inheritance
JavaScript is not strictly class-based like Java or C++, but rather a prototype-based language. However, ES6 introduced the class syntax to make Object-Oriented Programming (OOP) much more accessible.
The Class Keyword
A class acts as a blueprint. It encapsulates data (properties) and behavior (methods) into a single logical entity. When you define a class, you are defining what future objects created from this class will look like and how they will behave.
The Constructor & "this"
The constructor() method is a special function inside the class that gets called immediately when you create a new instance using the new keyword. Inside the constructor, we use the keyword this to refer to the specific instance being created, allowing us to assign its initial properties.
Inheritance & Super
We can create parent-child relationships between classes using extends. A child class inherits the methods of its parent. If the child has its own constructor, it must call super() before it can use this. This ensures the parent class sets up its part of the object first.
Dive Deeper: Encapsulation+
In modern JavaScript, you can define private properties and methods by prefixing them with a hash (#). This enforces encapsulation, meaning the data cannot be manipulated directly from outside the class, preventing accidental mutations and keeping the internal state secure.
