Skip to content

extends & super

The extends keyword creates a class that inherits from another class (the parent). super is used to call the parent’s constructor and methods.

class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // call parent constructor
this.breed = breed;
}
bark() {
return `${this.name} barks loudly!`;
}
}
const rex = new Dog('Rex', 'Labrador');
console.log(rex.speak()); // "Rex makes a sound" — inherited
console.log(rex.bark()); // "Rex barks loudly!" — own method
class Animal {
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks!`; // overrides parent
}
}
const rex = new Dog('Rex');
console.log(rex.speak()); // "Rex barks!" — Dog's version
class Animal {
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
// Call parent method, then extend it
const parentMessage = super.speak();
return `${parentMessage} — specifically, it barks!`;
}
}
const rex = new Dog('Rex');
console.log(rex.speak());
// "Rex makes a sound — specifically, it barks!"
flowchart TD
A["Animal\n- constructor(name)\n- speak()"]
B["Mammal extends Animal\n- constructor(name, hasFur)\n- walk()"]
C["Dog extends Mammal\n- constructor(name, breed)\n- bark()"]
D["rex = new Dog('Rex', 'Lab')"]
A --> B --> C
C --> D
D -.->|"rex.speak() → Animal.prototype"| A
D -.->|"rex.walk() → Mammal.prototype"| B
D -.->|"rex.bark() → Dog.prototype"| C
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // ✅ Required before this
this.breed = breed;
}
}
// Without super:
class BadDog extends Animal {
constructor(name, breed) {
// ❌ ReferenceError: Must call super first
this.breed = breed;
super(name);
}
}

extends works with any expression that returns a constructor:

function createBase(prefix) {
return class {
greet() { return `${prefix}: Hello!`; }
};
}
class Specific extends createBase('API') {
// ...
}
const obj = new Specific();
console.log(obj.greet()); // "API: Hello!"
  • extends creates a parent-child class relationship
  • super() calls the parent constructor (required before this)
  • super.method() calls a parent method
  • Method overriding replaces parent behavior
  • extends can be used with expressions