Show contents
Chapter 4 of 6 · 20 min
Modules, classes and closures
By the end of this chapter, you'll be able to
- Split an application into modules with export and import
- Write a class with private fields, getters and static methods
- Protect state with a closure
- Avoid losing this when a method is passed as an argument
ES modules
A module is a JavaScript file that chooses what it exports. Everything else is private to it. Another module imports what it needs:
// api.js
const BASE = "https://api.example.org"; // private: invisible outside the module
export async function weather(city) {
const response = await fetch(`${BASE}/weather/${city}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
// main.js
import { weather } from "./api.js";
console.log(await weather("dakar"));
<script type="module" src="main.js"></script>
type="module"turns modules on in the page: each file has its own scope, strict mode is automatic, andawaitis allowed at the top level.export defaultexports a main value, imported without braces:import Basket from "./basket.js".- The labs run a single file: the following examples therefore put everything in one block, but each class could live in its own module.
Classes and private fields
class Basket {
#items = [];
static VAT = 0.18;
constructor(currency) {
this.currency = currency;
}
add(name, price, quantity = 1) {
if (price < 0 || quantity <= 0) throw new RangeError(`invalid item: ${name}`);
this.#items.push({ name, price, quantity });
return this;
}
get total() {
const net = this.#items.reduce((s, i) => s + i.price * i.quantity, 0);
return Math.round(net * (1 + Basket.VAT));
}
get count() {
return this.#items.reduce((s, i) => s + i.quantity, 0);
}
static fromList(currency, list) {
const basket = new Basket(currency);
for (const [name, price, quantity] of list) basket.add(name, price, quantity);
return basket;
}
}
const basket = new Basket("CFA francs").add("shea soap", 1500, 2).add("tea", 2000);
console.log(basket.count, "items,", basket.total, basket.currency);
const other = Basket.fromList("CFA francs", [["rice 5 kg", 4500, 1], ["oil", 1800, 2]]);
console.log(other.total);
console.log(Object.keys(basket));
try {
basket.add("error", -5);
} catch (e) {
console.log(e.name, e.message);
}
3 items, 5900 CFA francs
9558
["currency"]
RangeError invalid item: error
#itemsis a private field: only the class's code can read or change it.Object.keys(basket)doesn't even show it, andbasket.#itemsoutside the class is a syntax error.get total()is a getter: you use it like a property (basket.total), but its value is computed on every read.staticattaches a property or method to the class itself:Basket.VAT,Basket.fromList(…). A static method that builds an object is called a factory.addreturnsthis, which lets you chain calls.RangeErroris a predefined kind of error for a value outside the allowed range.
Closures
A function keeps access to the variables of the place where it was created, even after the function that held them has finished: that's a closure. It's the other very common way to protect state:
function createCounter(name) {
let value = 0;
return {
increment() { value += 1; return value; },
toString() { return `${name}: ${value}`; },
};
}
const visits = createCounter("visits");
const clicks = createCounter("clicks");
visits.increment();
visits.increment();
clicks.increment();
console.log(String(visits), "|", String(clicks));
console.log("value" in visits);
visits: 2 | clicks: 1
false
Each call to createCounter creates its own value variable, inaccessible from outside: only the two returned methods can read it.
visits.increment() changes its own value, and only that one. Nobody else can touch it.
Text description of the animation
- First call: a value variable is created, and the returned increment function keeps it with it.
- Second call: another value variable, independent of the first.
- visits.increment() changes its own value, and only that one. Nobody else can touch it.
Your turn
Mini-lab: a protected grade bookJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: an event emitter
Write an Emitter class that lets you subscribe to an event type with on(type, listener) and trigger all subscribers with emit(type, payload). on returns a function that cancels the subscription. Subscriptions must be private. Test with two subscribers to the "add" event, one of which unsubscribes.
Hint 1
#listeners = new Map() maps each type to a Set of functions.Hint 2
on can return an arrow function that removes the listener from the Set: it's a closure that remembers the type and the function.Show the solution and common mistakes
class Emitter {
#listeners = new Map();
on(type, listener) {
if (!this.#listeners.has(type)) this.#listeners.set(type, new Set());
this.#listeners.get(type).add(listener);
return () => this.#listeners.get(type).delete(listener);
}
emit(type, payload) {
for (const listener of this.#listeners.get(type) ?? []) listener(payload);
}
}
const basket = new Emitter();
const unsubscribe = basket.on("add", (item) => console.log("badge:", item));
basket.on("add", (item) => console.log("analytics:", item));
basket.emit("add", "tea");
unsubscribe();
basket.emit("add", "soap");
basket.emit("payment", 3500);
badge: tea
analytics: tea
analytics: soap
This small pattern is at the heart of many libraries: the components of a page subscribe to the changes that concern them, without knowing about each other. This course's project uses it.
Common mistakes:
- Storing listeners in an array and removing them with
indexOf: if the same function is added twice, behaviour becomes confusing. ASetprevents duplicates. - Forgetting
?? []inemit: triggering a type with no subscribers would crash withTypeError: … is not iterable.
Summary
- 1A module chooses what it exports; everything else is private to it. It is enabled with type="module".
- 2A class can have private fields (#), getters (get) and static members.
- 3A closure keeps access to the variables of the function that created it: another way to protect state.
- 4this depends on how a function is called: pass an arrow function or use bind.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.