JavaScript Fundamentals / Classes

Extends (Inheritance)

👶 Understanding Inheritance with Extends

The extends keyword allows one class to inherit from another — this is called subclassing.

This means the child class automatically gets access to the parent class’s:

  • properties (via constructor using super)

  • methods (from parent’s prototype)

  • getters/setters

  • static methods (if parent has them)

Syntax:

class ChildClass extends ParentClass {
  constructor(args) {
    super(args); // calls parent class constructor
    // child-specific properties
  }

  childMethod() {
    // method specific to ChildClass
  }
}

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // must call super() before using 'this'
    this.breed = breed;
  }
  
  showBreed() {
	  console.log(`Breed is ${this.breed}`)
	}
}

const myDog = new Dog("Rocky", "Labrador");
myDog.speak(); // Output: Rocky makes a noise.
myDog.showBreed(); // Output: Breed is Labrador

🧾 Explanation:

  • class Dog extends Animal

    → Dog inherits from Animal, meaning Dog.prototype is linked to Animal.prototype.

  • super(name)

    → calls the parent class constructor (Animal’s constructor) and assigns this.name = name.

    It must be called before using this in a subclass.

  • myDog

    → has access to:

    • name (from Animal constructor)

    • breed (from Dog constructor)

    • speak() (from Animal.prototype)

    • showBreed() (from Dog.prototype)


✅ Why do we need super(name) in Child Class Dog?

1) To run the parent constructor

Animal has:

constructor(name) {
  this.name = name;
}

So super(name) does:

✔ call Animal's constructor

✔ sets this.name = "Rocky" for the Dog object

Without it, the Dog will not get the name.


2) JavaScript requires it BEFORE using this

In a class that uses extends:

  • You cannot access this until super() is called

constructor(name, breed) {
  this.breed = breed; // ❌ ERROR: Must call super()
}

This will throw:

ReferenceError: Must call super constructor before accessing 'this'

Because:

✅ super() creates and initializes this

❌ Without it, this does not exist yet

3) It sets up inheritance correctly

super() ensures:

  • the object is linked to the parent prototype

  • inherited methods work

So after calling super():

myDog.speak(); // works because Dog inherits Animal methods