Skip to main content

Introduction to Classes

Object-Oriented Programming (OOP) allows you to organize code into conceptual objects. Before ES6 (2015), JavaScript relied purely on "Constructor Functions". Now, JavaScript provides the class keyword.

It's important to remember that class in JS is mostly syntactic sugar over prototypes; JavaScript remains historically a Prototype-based language.

Creating a Class

A class is essentially a blueprint used to generate multiple instantiated objects sharing the same methods.

class Player {
// The constructor fires immediately when a 'new' object is created
constructor(playerName, playerLevel) {
// 'this' refers to the unique instance being generated
this.name = playerName;
this.level = playerLevel;
this.health = 100;
}

// Methods are automatically assigned to the Object's Prototype
takeDamage(amount) {
this.health -= amount;
console.log(`${this.name} took ${amount} damage! Health: ${this.health}`);
}

levelUp() {
this.level++;
console.log(`Leveled up to ${this.level}!`);
}
}

// Creating INSTANCES from the blueprint
const player1 = new Player("Aragorn", 10);
const player2 = new Player("Legolas", 12);

player1.takeDamage(25); // Aragorn took 25 damage! Health: 75