Inheritance (extends)
JS · Classes & OOPsyntax
class Child extends Parent {
constructor(params) {
super(parentParams);
}
}example
class Shape {
constructor(color) {
this.color = color;
}
describe() {
return `A ${this.color} shape`;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
describe() {
return `A ${this.color} circle (r=${this.radius})`;
}
}
const c = new Circle("blue", 5);
console.log(c.describe());
console.log(c.area.toFixed(2));output
"A blue circle (r=5)"
"78.54"Note super() must be called in the child constructor before accessing this. Methods can be overridden. Use super.method() to call the parent version.