⚡ Lesson 17 of 30
Classes & OOP
Model real-world entities with JavaScript classes, constructors, methods, and access modifiers.
Class Declaration
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
console.log(`${this.name} says ${this.sound}!`);
}
}
const dog = new Animal("Rex", "Woof");
dog.speak(); // "Rex says Woof!"
Getters & Setters
class Temperature {
#celsius;
constructor(c) { this.#celsius = c; }
get fahrenheit() { return this.#celsius * 9/5 + 32; }
set fahrenheit(f) { this.#celsius = (f - 32) * 5/9; }
toString() { return `${this.#celsius}°C`; }
}
const temp = new Temperature(100);
console.log(temp.fahrenheit); // 212
temp.fahrenheit = 32;
console.log(temp.toString()); // 0°C
Private Fields (#)
ES2022 private fields (prefix #) cannot be accessed outside the class:
class BankAccount {
#balance = 0;
deposit(amount) { this.#balance += amount; }
withdraw(amount) {
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#balance -= amount;
}
get balance() { return this.#balance; }
}
const acc = new BankAccount();
acc.deposit(100);
console.log(acc.balance); // 100
Static Methods & Properties
class MathUtils {
static PI = 3.14159;
static circleArea(r) {
return MathUtils.PI * r * r;
}
}
console.log(MathUtils.PI); // 3.14159
console.log(MathUtils.circleArea(5)); // 78.53...
Inheritance with extends
class Shape {
constructor(color) { this.color = color; }
describe() { return `A ${this.color} shape`; }
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
area() { return Math.PI * this.radius ** 2; }
describe() { return `${super.describe()} (circle r=${this.radius})`; }
}
const c = new Circle("red", 5);
console.log(c.describe()); // "A red shape (circle r=5)"