ES6 Classes
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
return this.name + " says " + this.sound + "!";
}
static create(name, sound) {
return new Animal(name, sound);
}
get info() { return this.name + " (" + this.sound + ")"; }
}
const dog = new Animal("Rex", "Woof");
console.log(dog.speak()); // Rex says Woof!
Inheritance
class Dog extends Animal {
constructor(name, breed) {
super(name, "Woof"); // call parent constructor
this.breed = breed;
}
speak() {
return super.speak() + " *wags tail*"; // call parent method
}
fetch(item) { return this.name + " fetches " + item + "!"; }
}
const rex = new Dog("Rex", "Labrador");
console.log(rex.speak()); // Rex says Woof! *wags tail*
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // true
Private Fields & Static
class BankAccount {
#balance; // private — # prefix
constructor(initial) { this.#balance = initial; }
deposit(amount) {
this.#balance += amount;
return this;
}
withdraw(amount) {
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#balance -= amount;
return this;
}
get balance() { return this.#balance; }
}
const acc = new BankAccount(100);
acc.deposit(50).withdraw(30);
console.log(acc.balance); // 120
// acc.#balance // SyntaxError — truly private!
// Static:
class Counter {
static #count = 0;
static increment() { return ++Counter.#count; }
static getCount() { return Counter.#count; }
}
Counter.increment();
Counter.increment();
console.log(Counter.getCount()); // 2
⚡ Key Takeaways
- Classes are syntactic sugar over prototypes
- Always call super() first in subclass constructors
- Private fields (#field) are truly private — not accessible outside the class
- Static methods/fields belong to the class, not instances
- Getters/setters allow computed property-style access with logic
🎯 Practice Exercises
EXERCISE 1
Create a Shape base class with abstract area() and perimeter(). Extend with Circle, Rectangle, Triangle. Add a static compare(a, b) that returns the larger shape by area.