Class Syntax and Constructor
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — A Blueprint for Many Objects
Imagine building a whole team of Codémon. Each one is an object with the same three properties: `name`, `type` and `level`. Writing every object by hand means repeating the same shape again and again — and a single typo in a key (like `tpye` instead of `type`) silently breaks that Codémon:
const zap = { name: "Zap", type: "electric", level: 4 };
const aquachu = { name: "Aquachu", type: "water", level: 12 };
const pyrochu = { name: "Pyrochu", tpye: "fire", level: 8 };
console.log(zap.type);
console.log(pyrochu.type);A class solves this problem. It is a blueprint that describes the shape of an object only once. Its `constructor` receives the values and fills in the properties, so every Codémon built from it is guaranteed to have the same keys, spelled the same way:
class Codemon {
constructor(name, type, level) {
this.name = name;
this.type = type;
this.level = level;
}
}
const zap = new Codemon("Zap", "electric", 4);
const pyrochu = new Codemon("Pyrochu", "fire", 8);
console.log(zap.type);
console.log(pyrochu.type);Here is what happens step by step: 1. `class Codemon { ... }` declares the blueprint. 2. `new Codemon("Zap", "electric", 4)` creates a fresh empty object and runs the `constructor` with those three values. 3. Inside the constructor, `this.name = name` (and so on) stores each value as a property of that new object. Two objects, zero repetition, and no room for a typo: the keys are written once, in the class.
Exercise 2 — Anatomy of a Class
Every class follows the same general structure. Here is the pattern to remember:
class Name {
constructor(param1, param2) {
this.prop1 = param1;
this.prop2 = param2;
}
}1. The `class` keyword, followed by a name that starts with a capital letter by convention (`Codemon`, not `codemon`). 2. A special method called `constructor`: it runs automatically every time you write `new Name(...)`. 3. Inside the constructor, `this` refers to the new object being built, so `this.prop1 = param1` creates a property on it. 4. The constructor's parameters receive the values you pass between the parentheses of `new Name(...)`.
A property does not have to come straight from a parameter. The constructor can also compute a value from another one, or give every new object the same starting value:
class Codemon {
constructor(name, level) {
this.name = name;
this.level = level;
this.hp = level * 10;
this.fainted = false;
}
}
const zap = new Codemon("Zap", 4);
console.log(zap.hp);
console.log(zap.fainted);Here, `hp` is computed from `level`, and `fainted` always starts at `false`. Neither needs to be passed when creating a Codémon — only `name` and `level` do.
Exercise 3 — Quiz: What the Constructor Sets
What does this code print?
class Item {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const potion = new Item("Potion", 30);
console.log(potion.price);30"Potion"undefinedHint : Follow each parameter to the property it fills in.
Exercise 4 — Build the Blueprint
Complete the class so every Codémon gets a name and a level.
Hint : One special method runs at creation, and one keyword names the object being built.
Exercise 5 — Each Call Builds a Separate Object
Every time you write `new`, JavaScript runs the constructor from scratch and produces a brand-new object. Objects built from the same class are completely independent: changing one never affects the others, exactly like two object literals written separately:
class Codemon {
constructor(name, level) {
this.name = name;
this.level = level;
}
}
const zap = new Codemon("Zap", 4);
const aquachu = new Codemon("Aquachu", 12);
zap.level = 99;
console.log(zap.level);
console.log(aquachu.level);`zap.level = 99` only changed `zap`. `aquachu` still has its own `level` of `12`. That is the whole idea of a class: the blueprint is shared, but each object built from it owns its own properties. Write the shape once, then stamp out as many independent copies as you need.
Exercise 6 — Quiz: Independent Objects
What does the last line print?
class Counter {
constructor() {
this.n = 0;
}
}
const a = new Counter();
const b = new Counter();
a.n = 5;
console.log(b.n);05undefinedHint : Each new runs the constructor again for a separate object.
Exercise 7 — Defaults With Default Parameters
The `constructor` is a function like any other, so it accepts default parameters. Give a parameter a default value with `=`, and callers can simply skip it whenever the usual value is fine:
class Codemon {
constructor(name, type = "normal", level = 1) {
this.name = name;
this.type = type;
this.level = level;
}
}
const wild = new Codemon("Rockachu");
const trained = new Codemon("Metachu", "metal", 15);
console.log(wild.type + " Lv." + wild.level);
console.log(trained.type + " Lv." + trained.level);Here is how the two calls differ: 1. `new Codemon("Rockachu")` only passes a name, so `type` falls back to `"normal"` and `level` to `1`. 2. `new Codemon("Metachu", "metal", 15)` passes all three values, so the defaults are ignored.
Capital letters matter
Naming a class `Codemon` rather than `codemon` is only a convention, but every JavaScript developer follows it. A capital letter tells the reader: "this is a class, use `new` with it".
Exercise 8 — Compute at Creation
Give every Codémon an `hp` worth ten times its level, computed in the constructor.
Hint : The new property takes its name from what is printed, and ten times means multiplying.
Exercise 9 — Class Cheat Sheet
Match each element with its role.
class Codemon { }constructor(...) { }this.name = namenew Codemon("Zap")Exercise 10 — Codémon Blueprint
Write the blueprint the whole game will use to create Codémon, then stamp out a team from it.
Step 1: declare a class `Codemon` whose constructor takes a name, a type and a level, with the type defaulting to `"normal"` and the level to `1`. Step 2: the constructor also sets `hp` to the level times 10, and `wins` to 0. Step 3: create Zap (electric, level 4), Aquachu (water, level 12) and a wild Rockachu with only a name. Step 4: print one line per Codémon in the format `"name (type) Lv.X, Y HP, Z wins"`.
Expected output:
Zap (electric) Lv.4, 40 HP, 0 wins
Aquachu (water) Lv.12, 120 HP, 0 wins
Rockachu (normal) Lv.1, 10 HP, 0 wins// Write your class here
// Create the team here