JavaScript Tutorial · Classes and Modules · Lesson 29 of 44
JavaScript Inheritance
Extend classes, call super and override methods.
extends and super
A class can extend another and inherit its methods. In the child's constructor, call super(...) before using this:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${this.name} barks.`;
}
}
const rex = new Dog("Rex", "beagle");
console.log(rex.speak());
console.log(rex instanceof Dog, rex instanceof Animal);
Output
Rex barks. true true
Overriding methods
A child class can replace a parent method and still call the original with super.method():
class Logger {
format(msg) {
return `[log] ${msg}`;
}
}
class TimestampLogger extends Logger {
format(msg) {
return `2026-01-01 ${super.format(msg)}`;
}
}
console.log(new TimestampLogger().format("server started"));
Output
2026-01-01 [log] server started
instanceof
instanceof checks whether an object was created from a class (or one of its children).
Prototypes under the hood
Classes are syntax on top of JavaScript's prototype system: every object has a hidden link to another object it inherits from. Object.getPrototypeOf(obj) shows it. You rarely need prototypes directly, but they explain why methods are shared rather than copied into each instance.
class Shape {
area() { return 0; }
}
class Square extends Shape {
constructor(side) { super(); this.side = side; }
area() { return this.side ** 2; }
}
const s1 = new Square(2);
const s2 = new Square(3);
console.log(s1.area(), s2.area());
console.log(s1.area === s2.area); // one shared method on the prototype
console.log(Object.getPrototypeOf(s1) === Square.prototype);
Output
4 9 true true
Test yourself
In a child class constructor, what must you call before using this?
this.parent()super()base()Parent.call()
Show answer
Answer: super()