Classes: Syntax & Inheritance
Organize your code using object-oriented blueprints. Learn how to construct instances and share logic using ES6 class syntax.
What is a Class?
A class in JavaScript is a blueprint for creating objects. Introduced in ES6, it provides a much cleaner, more familiar syntax for object-oriented programming compared to older prototype-based constructor functions.
A class groups related data (properties) and behavior (methods) together into a single, reusable template.
The Constructor and 'new'
Every class has a special constructor() method. This function runs automatically whenever you create a new instance of the class.
To create an instance, you must use the new keyword, like const hero = new Player('Link'). The new keyword creates a fresh object, binds this to that new object, and returns it.
Inheritance (extends & super)
You can create a new class based on an existing one using the extends keyword. For example, class Warrior extends Player.
The child class inherits all methods from the parent. However, if the child class has its own constructor, it MUST call super() before it is allowed to use the this keyword. super() executes the parent's constructor first.
The Class Factory
Step through the code to see how the new keyword builds an instance, and how extends and super link a subclass to its parent.
The Class Factory
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A
classis a blueprint for creating objects. - The
constructor()runs automatically when you use thenewkeyword. - The
newkeyword creates the object and bindsthis. extendscreates a subclass that inherits from a parent.- You must call
super()in a subclass constructor before accessingthis.
Done with this concept?
Mark it complete to track your progress. No login needed.