Classes: The Blueprints of App

Classes: The Blueprints of App in JavaScript: JavaScript is an Object-Oriented language, but it uses "Prototypes" under the hood.

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, not userRole).
  • Super calls: If you extend a class, you MUST call super() in the constructor before using this.
  • Don't over-OOP: JavaScript is also a functional language. Don't use classes for things that could just be simple functions.

Practice Exercises

  1. The Shape Lab: Create a Rectangle class with width and height, and a method getArea().
  2. The Zoo: Create an Animal class and a Dog sub-class that extends it. Add a bark() method to the Dog.
  3. The Banking App: Create a BankAccount class with deposit() and withdraw() methods that update a private-ish balance.