ES6 Classes & Inheritance
📖 Concept
ES6 classes are syntactic sugar over JavaScript's prototypal inheritance. They provide a cleaner, more familiar syntax but work the same way under the hood.
Key features:
constructor()— Called when creating new instances withnew- Instance methods — Defined in the class body
staticmethods — Called on the class itself, not instancesextends— Inherit from a parent classsuper— Call the parent's constructor or methods- Getters/Setters — Computed properties
- Private fields (
#field) — Truly private properties (ES2022)
🏠 Real-world analogy: A class is like a blueprint for a house. You can build many houses (instances) from the same blueprint. extends is like modifying the blueprint to add a garage — the new blueprint inherits the original rooms.
💻 Code Example
1class Animal {2 // Private field (ES2022)3 #id;45 constructor(name, sound) {6 this.name = name;7 this.sound = sound;8 this.#id = Math.random().toString(36).slice(2);9 }1011 // Instance method12 speak() {13 return `${this.name} says ${this.sound}`;14 }1516 // Getter17 get info() {18 return `${this.name} (${this.sound})`;19 }2021 // Setter with validation22 set nickname(value) {23 if (value.length < 2) throw new Error("Too short!");24 this._nickname = value;25 }2627 // Static method28 static create(name, sound) {29 return new Animal(name, sound);30 }3132 // Private method33 #generateTag() {34 return `ANIMAL-${this.#id}`;35 }36}3738// Inheritance with extends39class Dog extends Animal {40 constructor(name, breed) {41 super(name, "Woof"); // MUST call super before using 'this'42 this.breed = breed;43 }4445 // Override parent method46 speak() {47 return `${super.speak()} (tail wagging)`;48 }4950 fetch(item) {51 return `${this.name} fetches the ${item}!`;52 }53}5455const rex = new Dog("Rex", "German Shepherd");56console.log(rex.speak()); // "Rex says Woof (tail wagging)"57console.log(rex.info); // "Rex (Woof)" — inherited getter58console.log(rex instanceof Dog); // true59console.log(rex instanceof Animal); // true60console.log(Dog.create); // undefined — static methods aren't inherited on instances
🏋️ Practice Exercise
Mini Exercise:
- Create a
BankAccountclass with private#balance, deposit, withdraw, and getBalance - Create a
SavingsAccountthat extendsBankAccountand adds interest calculation - Implement a
LinkedListclass with add, remove, and traverse methods - Create a
Validatorclass with static methods for email, phone, and password validation
⚠️ Common Mistakes
Forgetting to call
super()in a child class constructor BEFORE usingthis— throws ReferenceErrorThinking classes are hoisted like function declarations — they are NOT (similar to
let/constTDZ)Confusing static methods with instance methods —
staticmethods are on the class, not on instancesUsing arrow functions as class methods — they work as class fields but are NOT on the prototype (memory duplication)
Forgetting that
#privatefields are truly private — not accessible viathis['#field']or outside the class
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for ES6 Classes & Inheritance. Login to unlock this feature.