Classes and Objects
A class is the blueprint; objects are the live instances — each with its own state, all sharing the same behavior.
Intent & Description
🎯 Intent
Model real-world entities with both data and behavior in a single reusable unit that can be instantiated many times.
📋 Context
You need multiple things of the same shape — multiple users, products, connections — each holding its own state but all sharing the same methods. Without classes, you’re copying structures by hand and keeping them in sync.
💡 Solution
Define a class with properties (state) and methods (behavior). Instantiate with new — each instance gets its own copy of the state; methods are shared from the class definition. The class is the template; the object is the runtime reality.
Real-world Use Case
📌 TL;DR
Classes are blueprints, objects are instances. The foundation of every OOP system — define structure once, instantiate freely.
Advantages
- Reusable blueprints — define once, instantiate as many times as needed
- Encapsulates data and behavior together in one place
- Clear, self-documenting structure for entities and domain concepts
Disadvantages
- Overkill for simple data shapes where a plain object or struct would do
- Requires understanding of the instantiation model — new, constructor, prototype chain
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const user1 = new User('Alice', 'alice@example.com');
const user2 = new User('Bob', 'bob@example.com');
console.log(user1.greet()); // "Hello, Alice!"
console.log(user2.greet()); // "Hello, Bob!"