Lesson 25 of 34 · Classes & Errors
JavaScript Classes: Constructors, Getters and Setters
In the Objects chapter you built heroes with a factory function that returned an object literal. That works, but when your game needs hundreds of heroes, monsters and items that share the same shape and behaviour, JavaScript offers a dedicated tool: classes.
A class is a blueprint. You describe the data and methods once, then create as many objects (instances) from it as you like.
Defining a class
class Monster {
constructor(name, hp) {
this.name = name;
this.hp = hp;
}
roar() {
return `${this.name} roars!`;
}
}
const goblin = new Monster("Goblin", 30);
const troll = new Monster("Troll", 120);
console.log(goblin.roar()); // Goblin roars!
console.log(troll.hp); // 120
console.log(goblin instanceof Monster); // true
class Monster { ... }declares the blueprint. Class names are written in PascalCase.- The constructor runs automatically when you create an instance with
new. Inside it,thisis the brand-new object, and you set its properties. - Methods are written without the
functionkeyword. They're shared by all instances instead of being copied into each one.
Class fields
Properties that start with the same value for every instance can be declared directly in the class body as fields:
class Chest {
isOpen = false;
items = [];
open() {
this.isOpen = true;
}
}
Private fields
Sometimes data should not be changed from outside. Fields whose names start with # are private: they can only be used by code inside the class body.
class Vault {
#gold = 0;
deposit(amount) {
this.#gold += amount;
}
balance() {
return this.#gold;
}
}
const vault = new Vault();
vault.deposit(50);
console.log(vault.balance()); // 50
console.log(vault.gold); // undefined: the private field is invisible from outside
// vault.#gold = 1000; // SyntaxError: private field outside its class
Getters and setters
A getter is a method that is used like a property, so there are no parentheses when you read it. It's great for computed values:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const rect = new Rectangle(3, 4);
console.log(rect.area); // 12 (not rect.area())
A setter runs when you assign to the property, which makes it the perfect place for validation. Getters and setters are often paired with a private field that holds the real value:
class Player {
#name = "";
get name() {
return this.#name;
}
set name(value) {
this.#name = value.trim() || "Anonymous";
}
}
const p = new Player();
p.name = " ";
console.log(p.name); // Anonymous
Common mistakes
- Forgetting
new.Monster("Goblin", 30)throwsTypeError: Class constructor Monster cannot be invoked without 'new'. - Forgetting
this.inside methods:hpis a variable,this.hpis the property. - A setter that assigns to itself.
set name(v) { this.name = v; }calls the setter again and again until the stack overflows. Store the value in a differently named (usually private) field. - Calling a getter like a method.
rect.area()fails becauserect.areais already the number.
Assignment
Complete the Character class:
constructor(name, hp)setsnameandmaxHp, and stores the starting hit points in a private field#hp.hpdefaults to100.- A getter
hpreturns the current hit points. - A setter
hpstores a new value, but clamps it between0andmaxHp. - A getter
isAlivereturnstruewhile hp is above0. takeDamage(amount)lowers hp byamount(never below0).describe()returns a status line like"Ada (70/100 HP)".
const ada = new Character("Ada");
ada.takeDamage(30);
ada.describe(); // "Ada (70/100 HP)"
ada.hp = 500;
ada.hp; // 100 (clamped)Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Classes, objects and structs in other languages
- Python Classes and Objects: __init__, Methods and Attributes · Python
- Go Structs: Define Your Own Types · Go
- Java Classes and Objects: Constructors and new · Java
- C# Classes and Objects · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .