Classes
Create blueprints for objects using ES6 classes — define a class that can produce multiple objects with the same structure and behavior.
Classes
Object literals work for single objects, but what if you need to create many objects with the same structure? Classes are blueprints for creating multiple objects of the same type.
Defining a Class
class User {
// Class body
}
Creating Instances
class User {
// empty for now
}
var userOne = new User();
var userTwo = new User();
console.log(userOne); // User {}
console.log(userTwo); // User {}
The new keyword creates a new instance (object) from the class. Each instance is a separate object.
The Class Analogy
Class = Cookie cutter (blueprint)
Instance = Individual cookie (object)
One class → many instances
Each instance has the same structure but can hold different data
Classes vs Object Literals
| Feature | Object Literal | Class |
|---|---|---|
| Purpose | One-off objects | Blueprint for many objects |
| Reusability | Not reusable | Create unlimited instances |
| Syntax | { key: value } | class Name { } |
| Creation | Direct | new ClassName() |
Naming Convention
Class names start with an uppercase letter by convention: User, Article, BlogPost. This distinguishes them from regular variables and functions.
Key Takeaways
- Classes are blueprints for creating objects with the same structure
new ClassName()creates a new instance of the class- Each instance is a separate object in memory
- Class names use PascalCase by convention