JavaScript: constructor
A class constructor initializes a new object when new creates an instance.
What you will learn
- How a
constructorruns whennewis used - How arguments set initial values
- How
thisrefers to the instance being created
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
- Use
this.namewhen you want a value to belong to each instance. - A class can have one constructor method; give it the exact name
constructor. - Do not confuse a constructor with an ordinary method that you call later.