Learn JavaScript · lesson 53 of 60 · about 8 minutes
Classes and Constructors
Write a blueprint once and make as many objects from it as you like.
What you'll learn
- Define a class with a constructor
- Create objects with new
- Store values on this
Bug Hunt
Sam is adding a little game to the page: Bug Hunt, about the bugs in Sam's own code. Every bug has a name and some hp, how much work it takes to fix, and there are lots of them, so each one should be an object of the same shape. That's what a class is for. bugList gives the bugs as pairs like ["Typo", 3], and the page starts by listing them: 3 bugs to fix: Typo, Off by one, Infinite loop (17 hp in all).
A blueprint for objects
When you need many objects with the same shape, like lots of players, write a class: a blueprint for them.
The class's constructor runs every time you make a new object with new. Inside it, this is the new object, so this.name = name stores the name on it.
Making players
class Player {
constructor(name, level) {
this.name = name;
this.level = level;
}
}
const ada = new Player("Ada", 3);
const bo = new Player("Bo", 7);
console.log(ada.name, ada.level);
console.log(bo.name, bo.level);Output
Ada 3
Bo 7Each object is separate
Every new makes a brand-new object. Changing one player's level doesn't touch the others, and instanceof tells you which class an object was made from.
Separate objects
class Counter {
constructor() {
this.count = 0;
}
}
const a = new Counter();
const b = new Counter();
a.count += 5;
console.log(a.count, b.count);
console.log(a instanceof Counter);Output
5 0
trueRemembering where it started
The constructor can store more than it's given. A Bug keeps its hp, which goes down as Sam works on it, and also startHp, a copy of how much it had at the start, so the page can later say Typo: 1 of 3 hp left. One bugList.map(([name, hp]) => new Bug(name, hp)) turns every pair into a Bug.
Tip
Class names start with a capital letter by convention: Player, not player. It tells readers to use new with it.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.