super Wires Constructor And Method Chains
super() must run before this exists in a subclass constructor, and super.method() reaches the parent implementation from an override.
Code
class Storage {
constructor(capacityMb) {
if (capacityMb <= 0) throw new Error('capacity must be positive');
this.capacityMb = capacityMb;
}
describe() {
return `${this.capacityMb} MB`;
}
}
class UsbStick extends Storage {
constructor(capacityMb, vendor) {
super(capacityMb); // must run before touching this
this.vendor = vendor;
}
describe() {
return `${this.vendor} stick, ${super.describe()}`;
}
}
const stick = new UsbStick(64000, 'Kestrel');
console.log(stick.describe());
console.log(stick instanceof UsbStick, stick instanceof Storage);Output
Captured from a sandboxed run of this snippet in the build pipeline.
Kestrel stick, 64000 MB
true trueHow it works
The code’s whole job belongs to the classes Storage and UsbStick.
A guard precedes the Error: bad state stops the flow there instead of continuing.
Everything operates on top-level bindings: stick.
Watch out for
- No package installation, no environment variables, no setup steps.
- The guard
capacityMb <= 0short-circuits the flow with an earlythrowwhen its condition holds.
The key statements that remain
if (capacityMb <= 0) throw new Error('capacity must be positive');
return `${this.vendor} stick, ${super.describe()}`;
return `${this.capacityMb} MB`;
Interactive Tools for This Topic
FAQ
- What does the snippet do with malformed data?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `stick`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.