JavaScript Classes & OOP
Master modern class syntax, constructors, inheritance with extends & super, true private fields (#), and static methods.
1. What is a Class?
A class is a blueprint for creating objects with shared properties and methods. In JavaScript, classes are simply a cleaner, modern syntax over prototypes!
💡 Think of an Architectural Blueprint
An architect draws a blueprint for a house once. From that one blueprint, you can build 50 houses (instances). Every house has the same layout and doors (methods), but can have different resident names and paint colors (properties)!
class User {
// 1. The constructor sets up properties when 'new User()' runs:
constructor(name, role) {
this.name = name;
this.role = role;
}
// 2. Class Method (automatically added to User.prototype):
describe() {
return `${this.name} works as a ${this.role}`;
}
}
const user1 = new User("Alex", "Engineer");
console.log(user1.describe()); // "Alex works as a Engineer"
console.log(typeof User); // "function" (Classes are constructor functions under the hood!)
Alex works as a Engineer function
2. Inheritance: `extends` & `super()`
You can create a specialized child class that inherits everything from a parent class using extends. Inside the child constructor, calling super() runs the parent constructor:
class Character {
constructor(name, health) {
this.name = name;
this.health = health;
}
attack() {
return `${this.name} attacks!`;
}
}
class Wizard extends Character {
constructor(name, health, spell) {
super(name, health); // ⚡ MUST call super() before accessing 'this'!
this.spell = spell;
}
// Overriding the attack method (Polymorphism):
attack() {
return `${this.name} casts ${this.spell} 🔥`;
}
}
const gandalf = new Wizard("Gandalf", 100, "Fireball");
console.log(gandalf.attack()); // "Gandalf casts Fireball 🔥"
console.log(gandalf.health); // 100 (Inherited from Character!)
Gandalf casts Fireball 🔥 100
3. True Private Fields with `#` (Encapsulation)
Modern JavaScript lets you create true private variables by prefixing their names with #. They cannot be read or changed outside the class:
Public Field (Default)
Anyone can read and change account.name = "New" from outside.
Private Field (`#balance` 🔒)
Locked inside the class! Trying to access account.#balance throws a SyntaxError.
class BankAccount {
#balance = 0; // 🔒 True private field
constructor(initialDeposit) {
this.#balance = initialDeposit;
}
deposit(amount) {
this.#balance += amount;
return this.#balance;
}
// Getter to safely read balance:
get balance() {
return `$${this.#balance}`;
}
}
const myAccount = new BankAccount(500);
myAccount.deposit(200);
console.log(myAccount.balance); // "$700"
// ❌ Accessing private field outside causes error:
// console.log(myAccount.#balance); // SyntaxError!
$700
4. Static Methods: Helper Tools on the Class Itself
A static method belongs to the class itself, not individual instances. You call it directly as ClassName.methodName():
class MathHelper {
static add(a, b) {
return a + b;
}
static PI = 3.14159;
}
// Call directly on the class — no need for 'new MathHelper()'
console.log(MathHelper.add(10, 20)); // 30
console.log(MathHelper.PI); // 3.14159
30 3.14159
5. Quick Class Summary
| Keyword / Feature | Purpose | Example |
|---|---|---|
constructor() |
Initializes properties when new Class() runs |
constructor(name) { this.name = name; } |
extends |
Inherits from a parent class | class Dog extends Animal {} |
super() |
Calls the parent constructor | super(name); |
#privateField |
Hides internal data from external access | #pinCode = 1234; |
static |
Attaches utility method directly to the class | MathHelper.add(2, 3) |
6. Classes Interview Deck
Test your knowledge on class types, super() invocation rules, private fields, static methods, and polymorphism:
7. Practice Challenge
🎯 Coding Challenge: User & Admin Classes
1. Build a User class with a private #password field and a verifyPassword(input) method.
2. Extend it with an AdminUser child class that passes arguments to super() and adds an admin level property.
3. Instantiate AdminUser and verify its password check.