Your First Class

Sophomore Year, page 2 of 11. A one-minute read.

Here's a class for game characters:

JavaScript
class Character {
  constructor(name, health) {
    this.name = name;
    this.health = health;
    this.level = 1;
  }

  attack() {
    console.log(`${this.name} attacks! ⚔️`);
  }

  levelUp() {
    this.level++;
    this.health += 20;
    console.log(`✨ ${this.name} reached level ${this.level}! Health is now ${this.health}.`);
  }
}

const hero = new Character("Mia", 100);
const sidekick = new Character("Omar", 80);

hero.attack();
sidekick.attack();
hero.levelUp();

console.log(hero);
console.log(sidekick);

It prints

Mia attacks! ⚔️
Omar attacks! ⚔️
✨ Mia reached level 2! Health is now 120.
Character { name: 'Mia', health: 120, level: 2 }
Character { name: 'Omar', health: 80, level: 1 }

Let's break it down:

  • class Character { ... } creates a class called Character. By convention, class names start with a capital letter (this is called PascalCase), so you can tell them apart from normal variables and functions.
  • constructor(name, health) is a special method that runs automatically every time you create a new instance. Its job is to set up the new object's starting properties.
  • Inside the constructor, this refers to the brand-new object being created. So this.name = name means "give this new character a name property, set to whatever was passed in."
  • attack() and levelUp() are methods. Every instance gets them. Notice there are no commas between methods in a class, unlike in an object.
  • new Character("Mia", 100) creates a new instance. The arguments go to the constructor.

Notice that hero and sidekick are completely separate objects. Leveling up Mia doesn't affect Omar. They were made from the same cookie cutter, but they're different cookies.

Watch outDon't forget new

If you forget the new keyword, JavaScript refuses to create the object:

JavaScript
class Cat {
  constructor(name) {
    this.name = name;
  }
}

const tom = Cat("Tom");

It stops with an error

Uncaught TypeError: Class constructor Cat cannot be invoked without 'new'

Always use new with classes.

instanceof

You can check whether an object was made from a particular class with instanceof:

JavaScript
console.log(hero instanceof Character);
console.log({ name: "Imposter" } instanceof Character);

It prints

true
false

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning