JavaScript: constructor

A class constructor initializes a new object when new creates an instance.

What you will learn

Minimal example

class Player {
  constructor(name, hp) {
    this.name = name;
    this.hp = hp;
  }

  showStatus() {
    console.log(`${this.name} has ${this.hp} HP`);
  }
}

const hero = new Player("Yuki", 100);
hero.showStatus();

When new Player("Yuki", 100) runs, JavaScript creates an instance and calls the constructor with those arguments. Inside the constructor, this points to that new instance.

Common mistakes