A class is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods) into a single unit.
JavaScript
class Player {
// The constructor runs automatically when 'new' is called
constructor(name, level) {
this.name = name;
this.level = level;
}
// This is a Method (automatically placed on Player.prototype)
levelUp() {
this.level++;
console.log(`${this.name} is now level ${this.level}!`);
}
}
const p1 = new Player("Aragon", 10);
p1.levelUp(); // "Aragon is now level 11!"
extends and superOne of the biggest advantages of classes is how easily they handle inheritance. You can create a “Child” class that inherits everything from a “Parent” class.
extends: Links the child’s prototype to the parent’s prototype.super(): A special function that calls the constructor of the parent class. It must be called before using this in a child constructor.JavaScript
class Character {
constructor(name) {
this.name = name;
this.health = 100;
}
}
class Mage extends Character {
constructor(name, spell) {
super(name); // Calls Character constructor
this.spell = spell;
}
cast() {
console.log(`${this.name} casts ${this.spell}!`);
}
}
const gandalf = new Mage("Gandalf", "Fireball");
console.log(gandalf.health); // 100 (Inherited)
gandalf.cast(); // "Gandalf casts Fireball!"
Getters and setters allow you to define methods that look like properties. This is useful for data validation or computed properties.
JavaScript
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
// Getter
get area() {
return this.width * this.height;
}
// Setter
set width(value) {
if (value <= 0) console.error("Width must be positive!");
else this._width = value;
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // 50 (Accessed like a property, not rect.area())
Static members belong to the class itself, not to the instances (objects) created from the class. They are often used for utility functions.
JavaScript
class MathHelper {
static pi = 3.14;
static calculateCircleArea(radius) {
return this.pi * radius * radius;
}
}
console.log(MathHelper.pi); // 3.14
// const helper = new MathHelper();
// helper.calculateCircleArea(5); // Error! Not a function on the instance.
#)Historically, JS developers used underscores (e.g., _password) to signal that a property was private. Now, JavaScript has native private fields using the # symbol. These cannot be accessed outside the class.
JavaScript
class BankAccount {
#balance = 0; // Private field
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
this.#balance += amount;
}
showBalance() {
console.log(`Balance for ${this.owner}: $${this.#balance}`);
}
}
const myAcc = new BankAccount("John");
myAcc.deposit(500);
// console.log(myAcc.#balance); // Syntax Error: Private field must be accessed within class
myAcc.showBalance(); // Works!
Modern Object-Oriented Programming (OOP) uses classes as blueprints to create objects that model real-world entities.
Classes provide:
Even in JavaScript, classes are a clean abstraction over prototypes.
A class is a blueprint that defines:
Example (conceptual):
class User {
name
login()
}
| Aspect | Class | Object |
|---|---|---|
| Meaning | Blueprint | Instance |
| Memory | No data | Actual data |
| Created using | class | new |
class ClassName {
constructor() {}
method() {}
}
thispublicprivateprotectedUsed to implement encapsulation.
Encapsulation ensures:
Example (conceptual):
private balance
public deposit()
Inheritance allows a class to reuse and extend another class.
extends Keywordclass Admin extends User
super KeywordPolymorphism allows:
Same method name → different behavior
Achieved via:
Hiding implementation details and showing only essential features.
Implemented using:
| Aspect | Inheritance | Composition |
|---|---|---|
| Relationship | “is-a” | “has-a” |
| Flexibility | Low | High |
| Coupling | Tight | Loose |
👉 Modern OOP prefers composition.
Returning this enables chained calls.
Example:
user.setName().setAge().save()