Skip to main content

Command Palette

Search for a command to run...

The Club Blueprint: Mastering OOP in JavaScript 🏗️

Updated
3 min readView as Markdown
The Club Blueprint: Mastering OOP in JavaScript 🏗️

Object-Oriented Programming (OOP) is a programming style based on the concept of "objects," which can contain data and code. Instead of writing messy, scattered functions, we group everything related to a specific "thing" into one structure.

1. The Blueprint Analogy (Class vs. Object)

Imagine you are the architect of a new football stadium.

  • The Class: This is your Blueprint. It’s the drawing that says "Every stadium must have a pitch, seats, and a scoreboard." You can't play football on a blueprint.

  • The Object (Instance): This is the Actual Stadium built from that blueprint (like the Santiago Bernabéu). You can build many stadiums from one single blueprint.


2. What is a Class in JavaScript?

A Class is the blueprint we use to create objects. It defines what properties (data) and methods (actions) the objects will have.

class Player {
    // The Constructor is the "Setup" phase
    constructor(name, pace, shooting) {
        this.name = name;
        this.pace = pace;
        this.shooting = shooting;
    }

    // This is a Method (an action the player can do)
    celebrate() {
        console.log(`${this.name} runs to the corner flag and shouts SIUUUUU! 🐐`);
    }
}

The Constructor Method

The constructor is a special function that runs automatically the moment you create a new object. It takes the "specs" (like name and pace) and assigns them to the player using the this keyword.


3. Creating Objects (Instantiating)

Once you have your Player class, creating a new superstar is as easy as using the new keyword.

const ronaldo = new Player("Cristiano Ronaldo", 90, 94);
const bellingham = new Player("Jude Bellingham", 82, 78);

console.log(ronaldo.name); // "Cristiano Ronaldo"
ronaldo.celebrate(); // Output: Cristiano Ronaldo runs to... SIUUUUU!

4. The Power of Encapsulation (Briefly)

Encapsulation sounds fancy, but it just means keeping data and the methods that work on that data together in one box (the class).

Instead of having a random calculatePace() function floating around your code, it lives inside the Player class. This keeps your "clubhouse" clean and prevents other parts of your code from accidentally breaking player stats.


🏆 Daily Drill: The Student Academy

Head to your console and build your own "Player Academy" using classes:

  1. Create a class called Student.

  2. The Constructor: Give it name and age properties.

  3. The Method: Add a method called introduce that prints: "Hi, my name is [name] and I am [age] years old."

  4. Graduation: Create three different student objects (e.g., student1, student2, student3) using your class and call the introduce method for each.

Why is this better than creating 3 separate objects manually? Write your answer in the comments!