Extending a class in JavaScript
extends, super, and how instanceof sees the chain.
class Step {
constructor(title) {
this.title = title;
}
describe() {
return `step: ${this.title}`;
}
}
class Encore extends Step {
constructor(title, lines) {
super(title);
this.lines = lines;
}
describe() {
return `${super.describe()} (${this.lines} lines)`;
}
}
const encore = new Encore("crawler.go", 67);
console.log(encore.describe());
console.log(encore instanceof Encore, encore instanceof Step);
console.log(Object.getPrototypeOf(Encore) === Step);
How it works
super(...)must run beforethisis touched.- A method can call
super.method()to reach the parent's version. #privatemembers are not visible to a subclass.
Keywords and builtins used here
Objectclassconstconstructorextendsreturnsuperthis
The run, in numbers
- Lines
- 25
- Characters to type
- 460
- Tokens
- 128
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 81 seconds.
Step 3 of 3 in Classes, step 37 of 43 in Language basics.