Lesson 29 of 34 · Classes & Errors
JavaScript Classes Boss: The Clockwork Colossus
The Clockwork Colossus blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Deep in the Forge of Classes, the Clockwork Colossus grinds to life: built from blueprints, plated in armor, its gears hidden behind private fields. Now it challenges every hero to a duel.
Battle plan
You'll build a tiny duel engine that uses every idea from this chapter:
- A class with a private field and getters: a fighter's hit points live in
#hp, and the outside world can read them but never set them directly. - A custom error class: a defeated fighter who tries to attack throws a
DefeatedError. - Inheritance with
super: aGolemis aFighterwhose armor softens every hit. It reuses the parent'stakeHitinstead of duplicating it. - A static method that runs a whole duel between two fighters.
Watch out for two traps. First, armor must never heal: a hit weaker than the armor does 0 damage, not negative damage. Second, two well-armored golems might never hurt each other, so a duel needs a round limit or it would loop forever.
Assignment
class DefeatedError extends Error: its constructor takes a fighter's name. The error'snameis"DefeatedError"and itsmessageis"<name> cannot fight while defeated".class Fighter:constructor(name, hp, power)sets the public propertiesnameandpower, and storeshpin a private field.- getter
hpreturns the current hit points. There's no setter:fighter.hp = 999must not change anything. - getter
isDefeatedistruewhen hp is0. takeHit(damage)lowers hp bydamage, never below0.strike(target)makestargettake a hit equal to this fighter'spower. If this fighter is defeated, it throws aDefeatedErrorinstead.static duel(a, b): the fighters take turns striking,afirst. As soon as one of them is defeated, return the winner's name. If nobody has won after 100 rounds (a round is one strike each), return"draw".
class Golem extends Fighter:constructor(name, hp, power, armor)witharmordefaulting to2.- overrides
takeHit(damage)so that each hit is reduced byarmor, but never below0.
const ada = new Fighter("Ada", 20, 6);
const rocky = new Golem("Rocky", 30, 4); // armor 2
ada.strike(rocky);
rocky.hp; // 26 (6 - 2 armor = 4 damage)
Fighter.duel(ada, rocky); // "Rocky"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.
Keep learning
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .