What is a class? The Blueprint

Think of a class as a blueprint for creating objects. A blueprint for a car isn't a car itself; it's the detailed plan for how to build a car. It defines what a car is and what it can do.

An object (or instance) is the actual car you build from the blueprint. You can build many objects from one class, just like you can build many cars from one blueprint.

image.png

class Laptop {
  brand = "HP";
  ram = 8; 
  isPoweredOn = false;

  turnOn() {
    this.isPoweredOn = true;
    console.log("Laptop is booting up...");
  }
}

Creating an Object: Building from the Blueprint

To actually "build" a laptop from our Laptop class, we use the new keyword. This process is called instantiation.

image.png

let myLaptop = new Laptop();
let workLaptop = new Laptop();

console.log(myLaptop.brand); 
console.log(workLaptop.brand); 
myLaptop.turnOn(); 

The Problem: Notice that myLaptop and workLaptop are identical. They are both generic laptops. How do we create unique laptops with different specs right from the start? That's where the constructor comes in.

constructor

The constructor is a special method that runs automatically and only once when you create a new object. Its job is to set up the object's initial state by accepting arguments.

Think of it as the foreman on an assembly line who takes a specification sheet ("Dell", 16 GB RAM) and builds the product according to those specs.

image.png

class MusicPlayer {
  brand: string;
  storageGB: number;

  constructor(brandName: string, storageSize: number) {
    this.brand = brandName;
    this.storageGB = storageSize;
  }
}

let walkman = new MusicPlayer("Sony", 128);
let ipod = new MusicPlayer("Apple", 256);

console.log(walkman.brand); 
console.log(ipod.brand); 

The this Keyword

You might be wondering what this means.

this refers to the specific object instance being created.