Skip to main content

🍪 Classes

Cookie cutters for creating objects

The Blueprint Analogy

Think about building houses:

An architect creates ONE blueprint, but builders can construct MANY houses from it. The blueprint specifies:

  • How many rooms
  • Where the doors go
  • Window sizes
  • Plumbing layout

Each house built from that blueprint has the same structure, but different occupants, different furniture, different paint colors.

Classes are blueprints for objects.

  • The class defines the structure (what data it holds) and behavior (what it can do)
  • Objects are the actual "houses" - specific instances with their own data
  • One class → many objects

Why Do We Need Classes?

Without classes, you'd repeat yourself constantly:

// Creating "dog" data manually, over and over:
dog1_name = "Max"
dog1_breed = "Labrador"
dog1_age = 3

dog2_name = "Bella"
dog2_breed = "Poodle"
dog2_age = 5

dog3_name = "Charlie"
dog3_breed = "Beagle"
dog3_age = 2

Problems:

  • Repetitive code
  • Easy to forget a property
  • Hard to ensure every dog has the same structure
  • Hard to add behaviors (how does a dog bark?)

With classes, you define the structure once:

Class Dog:
  - has a name
  - has a breed
  - has an age
  - can bark()
  - can fetch()

Then create as many dogs as you want, with a consistent structure!


The Four Parts of a Class

Think of a class like a form template:

PartWhat It DoesReal-World Example
NameIdentifies the class"Dog", "BankAccount", "User"
PropertiesData it holdsname, age, balance
ConstructorSets up new objects"When creating, ask for name and age"
MethodsActions it can performbark(), deposit(), login()

Properties vs Methods: Nouns vs Verbs

Properties are the data (nouns):

  • What IS the thing?
  • name, age, color, balance, email

Methods are the actions (verbs):

  • What can the thing DO?
  • run(), eat(), bark(), withdraw(), sendMessage()

Example - A Car:

Properties (Data)Methods (Actions)
color: "red"start()
speed: 0accelerate()
fuel: 50brake()
brand: "Toyota"refuel()

A Simple Example (Explained)

Let's create a Dog class step by step:

class Dog {
  // Constructor: runs when you create a new dog
  constructor(name, breed) {
    this.name = name; // Store the name
    this.breed = breed; // Store the breed
  }

  // Method: what the dog can do
  bark() {
    console.log(this.name + " says woof!");
  }
}

What's happening here?

  1. class Dog - We're defining a blueprint called "Dog"
  2. constructor(name, breed) - When someone creates a dog, they typically provide name and breed
  3. this.name = name - Save the name to THIS specific dog being created
  4. bark() - Every dog can bark. It uses its own name.

Creating dogs from the blueprint:

const max = new Dog("Max", "Labrador");
const bella = new Dog("Bella", "Poodle");

max.bark(); // "Max says woof!"
bella.bark(); // "Bella says woof!"

Same class, different dogs, different names - but they all know how to bark!


The 'this' Keyword Explained

this is a word that can confuse a lot of people. Here's a simple explanation:

this means "the specific object we're working with right now"

Think of it like saying "my" or "I" in conversation:

  • Person 1 says: "My name is Alice" → this.name = "Alice"
  • Person 2 says: "My name is Bob" → this.name = "Bob"

Same sentence, but my refers to different people depending on who's talking.

class Person {
  constructor(name) {
    this.name = name; // "my name is..."
  }

  introduce() {
    console.log("Hi, I'm " + this.name); // "I'm..."
  }
}

const alice = new Person("Alice");
const bob = new Person("Bob");

alice.introduce(); // "Hi, I'm Alice" - 'this' is alice
bob.introduce(); // "Hi, I'm Bob" - 'this' is bob

Real-World Use Cases

1. User Accounts

Every user has the same structure but different data:

  • Properties: username, email, password, joinDate
  • Methods: login(), logout(), updateProfile()

2. Products in a Store

Every product has:

  • Properties: name, price, quantity, description
  • Methods: applyDiscount(), checkStock(), sell()

3. Game Characters

Every character has:

  • Properties: health, position, speed, inventory
  • Methods: move(), attack(), useItem(), takeDamage()

4. Messages

Every message has:

  • Properties: sender, recipient, content, timestamp
  • Methods: send(), markAsRead(), delete()

Class vs Object: The Key Difference

ClassObject
BlueprintActual thing
TemplateInstance
RecipeThe meal you made
Cookie cutterThe cookie
Form templateFilled-out form

You can't eat a recipe - you eat the meal made FROM the recipe.

You can't pet "Dog class" - you pet a specific dog made FROM the class.


Common Mistakes

Mistake 1: Forgetting 'this'

class Counter {
  constructor() {
    this.count = 0;
  }

  increment() {
    count++; // ❌ Wrong! 'count' doesn't exist
    this.count++; // âś… Correct! Use 'this.count'
  }
}

Why it happens: You forget that properties belong to the object, not floating in space.

Mistake 2: Using a Class When You Don't Need One

Not everything needs a class. Simple functions work fine for simple tasks:

// Overkill - a class for one function
class MathHelper {
  add(a, b) {
    return a + b;
  }
}

// Just use a function!
function add(a, b) {
  return a + b;
}

Rule of thumb: If you mainly need behavior (no state), a function is often enough.

Mistake 3: Making Everything Public

Some data should be private:

BankAccount:
  - balance: $5000 (should be private!)
  - withdraw(amount)
  - deposit(amount)

If balance is public, anyone can change it directly. Use getters/setters or private fields.


FAQ

Q: When should I use a class?

Use classes when you need to create multiple objects with the same structure and behavior. If you're building just one thing, or it has no state, a function might be better.

Q: What's the difference between class and object?

Class = blueprint/template. Object = actual instance created from the blueprint.

Q: Do all programming languages have classes?

Most modern languages do (JavaScript, Python, Java, C#). Some languages use different approaches like prototypes or structs.

Q: What is instantiation?

Creating an object from a class. "new Dog()" instantiates a Dog.

Q: What's the difference between a class and a function?

Functions just do things. Classes create things (objects) that have both data AND behavior. Classes can create multiple instances, each with their own data.

Q: Why is 'this' so confusing?

Because it changes meaning based on context. Just remember: this refers to "the current object" - whichever object is running the code at that moment.


Summary

Classes are blueprints that define the structure and behavior of objects. They're a way to create many similar things without repeating yourself.

Key Takeaways:

  • Class = blueprint, Object = instance
  • Properties = data (nouns), Methods = actions (verbs)
  • Constructor sets up new objects
  • this means "the current object"
  • Use classes when you need multiple objects with the same structure
  • Don't overcomplicate - sometimes a simple function is better

Classes are fundamental to object-oriented programming. Once you understand them, you can model almost anything in code!

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.