this in Classes
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — this Is the Instance Being Used
Imagine two Codémon built from the same class, each calling the same `describe()` method. The method's code is written only once, yet it prints two different names. The keyword that makes this possible is `this`:
class Codemon {
constructor(name) {
this.name = name;
}
describe() {
return "I am " + this.name;
}
}
const zap = new Codemon("Zap");
const aquachu = new Codemon("Aquachu");
console.log(zap.describe());
console.log(aquachu.describe());Inside a method, `this` always means the instance the method was called on — in other words, the object written before the dot: 1. In `zap.describe()`, `this` is `zap`, so `this.name` is `"Zap"`. 2. In `aquachu.describe()`, `this` is `aquachu`, so `this.name` is `"Aquachu"`. Same code, different object, different result.
Exercise 2 — this in the Constructor vs in a Method
`this` plays the same role in the constructor and in a method — it just shows up at different moments of the object's life: 1. In the constructor, `this` is the brand-new object being filled with its first values. 2. In a method, `this` is the existing object the method was called on. Same keyword, same object, seen at two different points in time:
class Codemon {
constructor(name, hp) {
this.name = name;
this.hp = hp;
console.log("Built: " + this.name);
}
heal(amount) {
this.hp = this.hp + amount;
console.log("Healed: " + this.name + " now has " + this.hp + " HP");
}
}
const zap = new Codemon("Zap", 20);
zap.heal(15);A property written with `this.` in the constructor (`this.hp = hp`) is exactly the same property read and updated with `this.` in every method afterwards (`this.hp = this.hp + amount`). That's how data set at creation stays available for the whole life of the instance.
Exercise 3 — Quiz: Who Is this?
What does this code print?
class Codemon {
constructor(name) {
this.name = name;
}
shout() {
return this.name.toUpperCase();
}
}
const metachu = new Codemon("Metachu");
console.log(metachu.shout());METACHUMetachuundefinedHint : Look at the object before the dot in the call.
Exercise 4 — Use this Twice
Complete the method so it works for any instance.
Hint : The method must refer to its own instance without naming any variable.
Exercise 5 — Returning this to Chain Calls
A method that ends with `return this` hands back the instance it was called on. Since the result is the instance itself, you can immediately call another method on it, one after another, in a single readable line:
class Codemon {
constructor(name) {
this.name = name;
this.level = 1;
this.hp = 10;
}
levelUp() {
this.level = this.level + 1;
return this;
}
heal(amount) {
this.hp = this.hp + amount;
return this;
}
}
const zap = new Codemon("Zap");
zap.levelUp().levelUp().heal(20);
console.log(zap.name + " Lv." + zap.level + ", " + zap.hp + " HP");Read the chain from left to right: 1. `zap.levelUp()` raises the level to `2` and returns `zap`. 2. `.levelUp()` is called on that result — still `zap` — raising the level to `3`. 3. `.heal(20)` is called on `zap` again, bringing its HP to `30`. You've already used this style on strings and arrays: `text.trim().toUpperCase()` works for exactly the same reason — each method returns something you can keep calling methods on.
Exercise 6 — Quiz: Chained Calls
What does the last line print?
class Counter {
constructor() {
this.n = 0;
}
add() {
this.n = this.n + 1;
return this;
}
}
const c = new Counter();
c.add().add().add();
console.log(c.n);310undefinedHint : Each call returns the same instance, so the next call lands on it too.
Exercise 7 — Keeping this Inside Callbacks
Inside a method, you will often need a callback — for example to loop over an array with `forEach`. Here is a classic trap: if you write that callback with the `function` keyword, `this` inside it is no longer your instance. A regular `function` always gets its own `this`, which here is `undefined`, so reading `this.name` crashes:
class Team {
constructor(name, members) {
this.name = name;
this.members = members;
}
announce() {
this.members.forEach(function (member) {
console.log(member + " joins team " + this.name); // error!
});
}
}
const squad = new Team("Sparks", ["Zap", "Aquachu"]);
squad.announce();The fix is to write the callback as an arrow function. Arrow functions don't have a `this` of their own: they simply keep the `this` of the place where they were written — here the `announce()` method, where `this` is the team:
class Team {
constructor(name, members) {
this.name = name;
this.members = members;
}
announce() {
this.members.forEach((member) => {
console.log(member + " joins team " + this.name);
});
}
}
const squad = new Team("Sparks", ["Zap", "Aquachu"]);
squad.announce();Rule of thumb
Inside a class method, always write callbacks as arrow functions. That way `this` keeps pointing at your instance, no matter which array method or timer ends up calling the callback.
Exercise 8 — Make It Chainable
Complete the method so that calls can be chained.
Hint : The method must return the instance itself, so the next call has something to land on.
Exercise 9 — this Cheat Sheet
Match each situation with what `this` is.
return thisExercise 10 — Fluent Trainer
Build a trainer whose methods can be chained into a single readable sentence, and whose callbacks can still reach the instance.
Step 1: `Trainer` takes a name. Its constructor sets `team` to an empty array and `badges` to 0. Step 2: `catchCodemon(name)` adds the name to the team and returns the instance. `earnBadge()` adds 1 to the badges and returns the instance. Step 3: `report()` prints `"name has N badges"`, then one line per team member as `"- member trained by name"`, using an arrow callback that reads the trainer's name through `this`. Step 4: create Sam, then in one chained line catch Zap, catch Aquachu, earn a badge, earn a badge, and report.
Expected output:
Sam has 2 badges
- Zap trained by Sam
- Aquachu trained by Sam// Write your class here
// Use it here