Concept Explanation
JavaScript is an Object-Oriented language, but it uses "Prototypes" under the hood. For a long time, this was very confusing. ES6 introduced the class keyword to make it look like other languages (like Java or Python).
Think of a Class as a Mould. You create the mould once (User), and then you can stamp out thousands of identical objects (Alice, Bob, Charlie).
Syntax or Core Structure
Basic Class Structure
class Player {
// 1. Initializer
constructor(name, score) {
this.name = name;
this.score = score;
}
// 2. Methods (Behaviors)
levelUp() {
this.score += 10;
console.log(`${this.name} is now at ${this.score}`);
}
}
const p1 = new Player("Artemis", 100);
p1.levelUp();
Inheritance (Extending)
class Admin extends Player {
deleteUser(user) {
console.log(`Admin ${this.name} deleted ${user}`);
}
}
Real World Example
A Game Engine: Every "Enemy" in a game belongs to an Enemy class. They all have a health property and a move() method, but each individual enemy can be at a different place on the screen.
Best Practices
- PascalCase: Class names must always start with a Capital Letter (
UserRole, notuserRole). - Super calls: If you extend a class, you MUST call
super()in the constructor before usingthis. - Don't over-OOP: JavaScript is also a functional language. Don't use classes for things that could just be simple functions.
Practice Exercises
- The Shape Lab: Create a
Rectangleclass withwidthandheight, and a methodgetArea(). - The Zoo: Create an
Animalclass and aDogsub-class that extends it. Add abark()method to the Dog. - The Banking App: Create a
BankAccountclass withdeposit()andwithdraw()methods that update a private-ishbalance.