Find a course

Module 1: Thinking in ObjectsLesson 2 of 1214 min

Classes, Constructors and Instances

Write classes with constructors and methods, create many instances with new, and see how each object keeps its own state while sharing one set of methods.

Step 1 of 14Learn

A blueprint for objects

An object literal is fine for one enemy. For two hundred, you want a class: a blueprint that describes what fields and methods every object of that kind has. Each object built from the class is an instance.

class Enemy {
  constructor(x, y, speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.health = 100;      // every enemy starts at full health
  }
  move() { this.x += this.speed; }
  takeDamage(amount) { this.health = Math.max(0, this.health - amount); }
  isAlive() { return this.health > 0; }
}

const a = new Enemy(0, 5, 2);
const b = new Enemy(30, 9, 3);
a.takeDamage(40);
// a.health is 60, b.health is still 100

Three pieces matter:

  • The constructor is a special method that runs once when an object is created. Its job is to put the new object into a valid starting state.
  • The keyword new creates an empty object, runs the constructor with this pointing at it, and hands the finished object back.
  • Methods are written once in the class but available on every instance. a.move() and b.move() run the same code; this decides whose x changes.

The class name starts with a capital letter by convention (Enemy, BankAccount), while instances use lowercase names (enemy, savings). That small habit makes code much easier to scan.

Step 2 of 14Practice · Fill in the blanks

Fill in the blanks

Complete the sentences. A is a blueprint; each object created from it is called an . The special method that sets up a new object's starting state is the , and in JavaScript you create an object by writing the keyword before the class name.

Word bank

Step 3 of 14Diagram

One class, many independent instances

One class, many independent instancesHierarchy diagram: class Enemy, a: x 0, health 60, b: x 30, health 100, c: x 12, health 100.class Enemya: x 0, health 60b: x 30, health 100c: x 12, health 100

Tap a shape with to see more.

Each instance stores its own field values; move(), takeDamage() and isAlive() are shared.
class Enemy

Defines the fields and holds the method code once.

a: x 0, health 60

a.takeDamage(40) changed only a.

b: x 30, health 100

Untouched by anything done to a.

c: x 12, health 100

Step 4 of 14Learn

The same class in Python

Different languages spell the same ideas differently. Here is Enemy in Python:

class Enemy:
    def __init__(self, x, y, speed):
        self.x = x
        self.y = y
        self.speed = speed
        self.health = 100

    def move(self):
        self.x += self.speed

    def take_damage(self, amount):
        self.health = max(0, self.health - amount)

a = Enemy(0, 5, 2)      # no "new" keyword in Python
a.take_damage(40)

The differences are surface-level:

  • Python's constructor is named __init__.
  • Python passes the object explicitly as the first parameter, named self by convention. JavaScript's this is implicit.
  • Python creates instances by calling the class like a function: Enemy(0, 5, 2).
  • Python naming style is take_damage (snake_case); JavaScript uses takeDamage (camelCase).

Java and C# look closer to JavaScript but require you to declare each field's type up front: private int health;. Whatever the syntax, the model is identical: a class defines fields and methods; instances hold their own field values; methods use this or self to reach the current instance.

Step 5 of 14Practice · Spot the mistake

This Python class should create a counter that starts at zero and goes up by one. Click the lines with mistakes.

Step 6 of 14Learn

Each instance has its own state

A common beginner surprise: changing one instance never changes another, because each instance has its own copy of the fields.

const p1 = new Player('Ana');
const p2 = new Player('Ben');
p1.score = 50;
console.log(p2.score);   // still 0

But watch out for references. Variables don't hold objects; they hold references (arrows) pointing at objects. Copying the variable copies the arrow, not the object:

const p3 = p1;      // p3 points at the SAME object as p1
p3.score = 80;
console.log(p1.score);   // 80

Now there is still only one Ana, reachable by two names. This is called aliasing. It's why p1 === p3 is true while two separately constructed players with identical fields are not equal with ===: equality on objects compares identity (same object?), not contents.

The same is true in Python (is checks identity), Java and C#. If you need a real copy, you must create a new instance, for example with a clone() method or a constructor that copies fields.

Step 7 of 14Practice · What would you do?

What would you do?

What does this code print?

const a = new Counter();   // count starts at 0
const b = a;
const c = new Counter();
b.increment();
b.increment();
c.increment();
console.log(a.count);

Step 8 of 14Diagram

References: two names, one object

References: two names, one objectParts diagram: Player { name: Ana, score: 80 }, p1 (reference), p3 = p1, p1 === p3 is true.Player { name:Ana, score: 80}p1 (reference)p3 = p1p1 === p3 istrue

Tap a shape with to see more.

p2 points at a different Player object, so it is unaffected.
Player { name: Ana, score: 80 }
p1 (reference)

Points at the Ana object.

p3 = p1

Copies the arrow, not the object. p3.score = 80 changed Ana.

p1 === p3 is true

Same object, same identity.

Step 9 of 14Practice · Code challenge

Write a class Rectangle whose constructor takes width and height and stores them as fields. Add two methods: area() returns width × height, and perimeter() returns 2 × (width + height).

Runs in a sandbox in your browser.
  • new Rectangle(3, 4).area()
  • new Rectangle(3, 4).perimeter()
  • new Rectangle(10, 0.5).area()
  • new Rectangle(2, 2).width

Step 10 of 14Note

Step 11 of 14Learn

What a class is not

Two misunderstandings trip up many learners at this stage.

First, a class is not a container of its instances. Writing class Enemy doesn't create a list of enemies, and the class doesn't automatically know how many instances exist. If you need all enemies, you keep them in an array or other collection yourself: const enemies = [new Enemy(0, 0, 1), new Enemy(5, 5, 2)].

Second, creating an instance doesn't copy the methods. Each enemy stores its own field values, but the method code exists once and is shared. That's why a game can create ten thousand instances cheaply: each one costs only the memory for its fields.

A useful mental picture is a cookie cutter and cookies. The cutter (class) defines the shape. Each cookie (instance) is separate: you can add frosting to one without changing the others. But the cutter is not a box of cookies, and pressing out a new cookie doesn't build a new cutter.

Finally, naming. Good class names are nouns that describe one kind of thing: Invoice, Player, TemperatureSensor. Good method names are usually verbs or questions: send(), addItem(), isExpired(). If a class name is a verb, such as ProcessOrder, it is probably a function pretending to be a class.

Step 12 of 14Practice · Sort into groups

Which names would make good class names, and which sound like methods?

Tap an item, then tap its group (or drag it there).

Step 13 of 14Flashcards

Class vocabulary

Tap a card to flip it.

Step 14 of 14Practice · True or false

Two instances created with new Point(1, 2) and new Point(1, 2) are equal when compared with === in JavaScript, because their fields match.