A family of classes
A savings account is a bank account, with interest. Instead of copying code, a class can extend another, inherit everything, and add or change just what's different.
extends and super
class Shape {
constructor(name) {
this.name = name;
}
area() {
return 0;
}
describe() {
return `${this.name} with area ${this.area()}`;
}
}
class Circle extends Shape {
constructor(r) {
super("Circle");
this.r = r;
}
area() {
return Math.round(Math.PI * this.r ** 2);
}
}
const c = new Circle(2);
console.log(c.describe());
console.log(c instanceof Circle, c instanceof Shape);class Animal {
speak() {
return "…";
}
}
class Cat extends Animal {
speak() {
return super.speak() + " meow!";
}
}
console.log(new Cat().speak());Prefer short inheritance chains (one or two levels). Deep hierarchies get hard to follow; combining small objects is often simpler.