Methods in Classes

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Behaviour Shared by Every Object

Imagine every Codémon needs an `attack()` action. If you write that function inside each object literal, every Codémon carries its own copy of the exact same code — and fixing a bug means fixing it in every single object:

const zap = { name: "Zap", attack() { return this.name + " attacks!"; } }; const aquachu = { name: "Aquachu", attack() { return this.name + " attacks!"; } }; console.log(zap.attack()); console.log(aquachu.attack());

In a class, a method is written once, right after the constructor, using the same short syntax as in an object literal. Every object built from the class can then call it:

class Codemon { constructor(name) { this.name = name; } attack() { return this.name + " attacks!"; } } const zap = new Codemon("Zap"); const aquachu = new Codemon("Aquachu"); console.log(zap.attack()); console.log(aquachu.attack());

One `attack()` for the whole class: change it in one place and every Codémon instantly gets the new behaviour. Inside the method, `this.name` reads the name of whichever Codémon called it — `zap` or `aquachu`.

Exercise 2 — Methods Take Parameters and Return Values

A class method is an ordinary function attached to the blueprint. Like any function, it can receive parameters and return a result. It can also combine those parameters with the object's own properties through `this`:

class Codemon { constructor(name, level) { this.name = name; this.level = level; } damage(base) { return base + this.level * 2; } } const zap = new Codemon("Zap", 4); console.log(zap.damage(10)); console.log(zap.damage(25));

`zap.damage(10)` returns `10 + 4 * 2`, which is `18`. Notice how the method mixes the argument it received (`base`) with the instance's own data (`this.level`). A class can hold as many methods as you need. One syntax detail to remember: unlike in an object literal, there is no comma between the methods of a class — they simply follow one another:

class Codemon { constructor(name, level) { this.name = name; this.level = level; } describe() { return this.name + " Lv." + this.level; } isVeteran() { return this.level >= 10; } } const metachu = new Codemon("Metachu", 15); console.log(metachu.describe()); console.log(metachu.isVeteran());

Exercise 3 — Quiz: Calling a Method

What does this code print?

class Item { constructor(price) { this.price = price; } discounted() { return this.price / 2; } } const potion = new Item(30); console.log(potion.discounted());
Options
• 15
• 30
• undefined
• An error

Hint : The method reads the object's own property and computes from it.

Exercise 4 — Add a Method

Give the class a `describe` method and call it.

Hint : The method name in the class must match the name used in the call, and no keyword is needed before it.

Exercise 5 — Methods That Change the Object

Methods don't just read properties — the most useful ones update the object they belong to. Since `this` is the instance the method was called on, writing `this.hp = this.hp - amount` changes that Codémon's real HP:

class Codemon { constructor(name, hp) { this.name = name; this.hp = hp; } takeDamage(amount) { this.hp = this.hp - amount; if (this.hp < 0) { this.hp = 0; } } } const zap = new Codemon("Zap", 45); zap.takeDamage(20); console.log(zap.hp); zap.takeDamage(100); console.log(zap.hp);

The first call lowers `zap.hp` from `45` to `25`. The second call would make it negative, so the `if` clamps it at `0`. Each call only touches the instance it was called on. A second Codémon built from the same class keeps its own HP untouched:

class Codemon { constructor(name, hp) { this.name = name; this.hp = hp; } takeDamage(amount) { this.hp = this.hp - amount; } } const zap = new Codemon("Zap", 45); const aquachu = new Codemon("Aquachu", 60); zap.takeDamage(20); console.log(zap.hp); console.log(aquachu.hp);

Exercise 6 — Quiz: After Two Calls

What does the last line print?

class Counter { constructor() { this.n = 0; } add() { this.n = this.n + 1; } } const c = new Counter(); c.add(); c.add(); console.log(c.n);
Options
• 2
• 0
• 1
• undefined

Hint : Each call updates the same object's property.

Exercise 7 — Heal Method

Complete the method so it raises the object's own HP by the amount.

Hint : Refer to the object without naming it, and add to the existing value rather than replacing it.

Exercise 8 — Methods Calling Methods

A method can call another method of the same object through `this`. This keeps each method small and focused, and lets you build bigger actions out of simple ones:

class Codemon { constructor(name, hp) { this.name = name; this.hp = hp; } isAlive() { return this.hp > 0; } status() { if (this.isAlive()) { return this.name + " is ready"; } return this.name + " has fainted"; } } const zap = new Codemon("Zap", 20); const pyrochu = new Codemon("Pyrochu", 0); console.log(zap.status()); console.log(pyrochu.status());

Follow `zap.status()` step by step: 1. Inside `status()`, `this` is `zap`. 2. `this.isAlive()` calls the `isAlive()` method on that same instance. It checks `zap.hp > 0` and returns `true`. 3. The `if` succeeds, so `status()` returns `"Zap is ready"`. For `pyrochu`, `isAlive()` returns `false` because its HP is `0`, so `status()` returns the fainted message instead.

Exercise 9 — Method Cheat Sheet

Match each element with its description.

Items to match
• attack() { }
• zap.attack()
• this.hp -= 10
• this.isAlive()
Definitions
• A method written once in the class
• Calls it on one object
• Changes that object's own property
• Calls another method of the same object

Exercise 10 — Battle-Ready Codémon

Give the Codémon blueprint the methods it needs to fight, then play a short duel.

Step 1: the class takes a name, a level and an hp. Add `attack(target)` which lowers the target's `hp` by this Codémon's level times 5, never below 0, and prints `"name hits target for X"`. Step 2: add `isAlive()` returning whether hp is above 0. Step 3: add `status()` returning `"name: X HP"`, or `"name: fainted"` when not alive. Step 4: Zap (level 4, 30 HP) and Metachu (level 8, 50 HP) each attack the other once, Metachu attacks again, then print both statuses.

Expected output:

Zap hits Metachu for 20 Metachu hits Zap for 40 Metachu hits Zap for 40 Zap: fainted Metachu: 30 HP
Starter code
class Codemon { constructor(name, level, hp) { this.name = name; this.level = level; this.hp = hp; } // Write your methods here } // Play the duel here
Back to the course