Classes, this, Modules and Errors
Group state and behaviour in classes with private fields, understand what this is bound to, split code into ES modules, and signal failures with real error types.
Contentsand lesson path
On this page
- Why it matters
- Classes group state with behaviour
- this depends on how the function is called
- Modules: explicit imports, shared instances
- Errors: throwing, catching, and your own types
- Check your understanding
- Apply it
- Review prompt
Lessons of JavaScript Foundations
- Values, Types and the Rules of Coercion Concept · 20 min
- Control Flow and Stepping Through Code with Breakpoints Worked example · 20 min
- Functions, Scope and Closures Concept · 25 min
- Shaping Data with Objects, Arrays, Map and Set Worked example · 30 min
- Classes, this, Modules and Errors Concept · 25 min
- Check: Predict the Output, Then Pass the Kata Tests Knowledge check · 8 questions
What you will learn
- Define and compose functions (arrow functions, default and rest parameters, higher-order functions, closures) and explain lexical scope and how this is bound.
- Organize code into ES modules and handle failures with exceptions and custom Error subclasses.
01. Why it matters
Four tools carry a program from "a file of statements" to "an application". Classes bundle state with the behaviour that owns it. this is the invisible parameter inside that behaviour, and misreading it is a reliable source of bugs. ES modules split code across files with explicit imports, so no file needs to know the order in which scripts were once pasted into a page. And errors are how code says "this did not work" — thrown, caught, and reported honestly instead of silently swallowed.
They belong in one lesson because they interlock: a module exports a class, the class’s methods read their state through this, and its methods throw errors that callers catch. The rate limiter used here is the kind of small component you will build for real: it allows two calls per second and refuses the rest.
02. Classes group state with behaviour
A class is a blueprint: new RateLimiter(2, 1000) runs the constructor and returns an object, an instance, with the class’s methods attached. A private field, declared with #, is state that only code inside the class body can touch — from outside, limiter.#calls is not merely undefined, it is a syntax error, so the class can promise what it will not expose. A getter such as remaining reads like a property but computes on access. Here it asks remainingAt for the count at the current time, dropping calls that have left the window first, so it never reports a stale value. The demo passes fake timestamps to allow and remainingAt instead of reading the clock, so its output is the same on every run.
class RateLimiter {
#calls = []; // private field: only code inside this class can read it
constructor(max, windowMs) {
this.max = max;
this.windowMs = windowMs;
}
#prune(now) { // private method: drop calls that left the window
this.#calls = this.#calls.filter((t) => now - t < this.windowMs);
}
remainingAt(now = Date.now()) {
this.#prune(now);
return Math.max(0, this.max - this.#calls.length);
}
get remaining() { // reads like a property, checks the real clock
return this.remainingAt();
}
allow(now = Date.now()) {
this.#prune(now);
if (this.#calls.length >= this.max) return false;
this.#calls.push(now);
return true;
}
}
const limiter = new RateLimiter(2, 1000);
console.log(limiter.allow(1000), limiter.allow(1100), limiter.allow(1200));
console.log(limiter.remainingAt(1200), limiter.remainingAt(5000));true true false
0 2Two permits, then refusal; no permits left at 1200 ms, and both back by 5000 ms, once the earlier calls have left the one-second window. The class keyword is not the only way to make such an object — the closure-based limiter in the functions lesson was one alternative — but a class says its shape in one glance, works well when there are many methods, and supports extends for sharing behaviour downward. A subclass constructor must call super(...) before touching this; the error class later in this lesson does exactly that.
03. this depends on how the function is called
For an ordinary method call, this is the object before the dot at call time (or before the brackets, in obj['greet']()). That rule explains both the power and the danger. player.greet() has player before the dot, so this is player. Take the same function out of context — const detached = player.greet; detached(); — and there is no dot: in a module, which always runs in strict mode, this is undefined and reading this.name throws.
Other kinds of call set this explicitly. new Fn() binds it to the fresh instance, which is how a constructor’s this.max = max works. fn.call(obj, a, b) and fn.apply(obj, [a, b]) pass it in for one call. And two escapes fix it for good: bind returns a new function with this fixed permanently. An arrow function has no this of its own; it uses the this of the code around it, which is why an arrow is the safe choice for a callback defined inside a method.
const player = {
name: 'Ada',
greet() {
return `I am ${this.name}`;
},
greetInArrow() {
const arrow = () => this.greet(); // an arrow takes "this" from greetInArrow
return arrow();
},
};
console.log(player.greet());
const detached = player.greet; // the method alone, no object in front of it
try {
detached();
} catch (err) {
console.log(err.constructor.name, '-', err.message);
}
console.log(player.greetInArrow());
console.log(player.greet.bind(player)());I am Ada
TypeError - Cannot read properties of undefined (reading 'name')
I am Ada
I am AdaLine two is the signature of a lost this. When you hand a method to something that will call it later — a DOM listener, a setTimeout, a promise chain — you are handing over the bare function, and the caller decides what this will be. Wrap the call in an arrow, as greetInArrow does, or use bind, and the binding survives.
04. Modules: explicit imports, shared instances
An ES module is a file with its own scope. Nothing leaks out except what you name in export, and the import side states exactly what it takes. A named export travels under its own name inside braces; a default export is the file’s single main thing and is imported without braces under any local name you choose. Top-level code in a module runs once, the first time any file imports it, and every importer sees the same instance — modules are shared, not copied.
export const RATES = { standard: 0.2, reduced: 0.05 };
export function withTax(amount, rate = RATES.standard) {
return amount * (1 + rate);
}
export default function round2(value) {
return Math.round(value * 100) / 100;
}import round2, { RATES, withTax } from './totals.mjs';
console.log(round2(withTax(50)));
console.log(round2(withTax(50, RATES.reduced)));60
52.5The default lands without braces, the named ones inside them. Shared instances have a consequence worth internalising: when a module changes one of its own top-level let variables (importers cannot reassign an imported binding, but they can call an exported function that does), every module that imports it sees the new value. That makes a module a convenient singleton — and a hazard when the mutable state is incidental. In the browser, modules load with <script type="module">. In Node.js, the dependable choices are the .mjs extension, or .js inside a project whose package.json declares "type": "module"; versions since 22.7 also detect import syntax in a plain .js file, but declaring the type removes the guess.
05. Errors: throwing, catching, and your own types
throw aborts the current path, and a try/catch offers a way back. Catching is a decision, not a reflex: handle the errors you can do something about and let the rest propagate, because an error silently converted into a log line hides a failure your caller needed to know about. A finally block runs when the try block exits by any route — success, caught error, or return — which makes it the home of cleanup.
For errors your domain defines, subclass Error. Call super(message) so the message and stack are recorded, set name so logs identify it, and add fields that carry what the caller needs. Then instanceof can tell your errors apart from built-in ones.
class ValidationError extends Error {
constructor(message, field) {
super(message); // sets message and captures the stack
this.name = 'ValidationError';
this.field = field;
}
}
function parseAge(raw) {
const n = Number(raw);
if (raw === '' || Number.isNaN(n) || n < 0) {
throw new ValidationError(`not an age: ${raw}`, 'age');
}
return n;
}
const inputs = ['42', '-3', 'abc'];
for (const raw of inputs) {
try {
console.log('age:', parseAge(raw));
} catch (err) {
if (err instanceof ValidationError) {
console.log(`invalid ${err.field}: ${err.message}`);
} else {
throw err; // not ours to handle: let it crash loudly
}
} finally {
console.log('checked', raw);
}
}age: 42
checked 42
invalid age: not an age: -3
checked -3
invalid age: not an age: abc
checked abcconst err = new ValidationError('not an age: abc', 'age');
console.log(
err instanceof ValidationError,
err instanceof Error,
err instanceof RangeError,
);
console.log(err.name, err.field, err.message);true true false
ValidationError age not an age: abcinstanceof walks the inheritance chain: a ValidationError is an Error, so a catch that filters on Error still receives it, and one that filters on a sibling type such as RangeError correctly rejects it. This is the error type the practice project of this skill asks you to raise for invalid records.
06. Check your understanding
07. Apply it
Move the orders work of the previous lesson into this shape, which is what the practice project expects:
- Put the validation helpers in
validate.mjsand the reporting inreport.mjs; import one from the other. Export a classOrderReportwith private fields for the valid and invalid lists, aget invalidCount(), and anadd(order)method that throws aValidationErrorwith afieldproperty for a bad record. - In
main.mjs, feed it one valid and two invalid orders, catch the errors, and print a per-record verdict. Add afinallythat logs how many records were processed, and check it runs on the success path too. - Detach a method —
const add = report.add; add(order)— and predict the failure before running. Fix it with an arrow wrapper.
Bundlers in the frontend tooling skill will merge module files for the browser; the import syntax you practise here is exactly what they consume.
08. Review prompt
Without looking back: state the rule that decides this in an ordinary method call, the three kinds of call that set it explicitly, and the two ways to keep it when the method is called by someone else. Explain what #field guarantees and at which moment it is enforced. Say what a module shares between its importers, and name the three things an error subclass constructor does (starting with super(message)). Finally, describe when finally runs and what makes an error worth catching.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.