AI Workshop: learn to build apps with AI →
OOP in JS: Inheritance

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


A class can extend another class, and objects initialized using that class inherit all the methods of both classes.

Suppose we have a class Person:

class Person {
  hello() {
    return 'Hello, I am a Person'
  }
}

We can define a new class Programmer that extends Person:

class Programmer extends Person {

}

Now if we instantiate a new object with class Programmer, it has access to the hello() method:

const flavio = new Programmer()
flavio.hello() //'Hello, I am a Person'

The JavaScript instanceof operator returns true if the first operand is an instance of the constructor passed on the right, or has it in its inheritance chain.

In this example, you can see that the myCar object, of class Fiesta, returns true for instanceof Fiesta, and also returns true for instanceof Car, because Fiesta extends Car:

class Car {}
class Fiesta extends Car {}

const myCar = new Fiesta()
myCar instanceof Fiesta //true
myCar instanceof Car //also true

In the constructor() method, we can also call super() to invoke the same method in the parent class.

Suppose you have a class Car:

class Car {

}

and in this class we have a constructor() method:

class Car {
  constructor() {
    console.log('This is a car')
  }
}

You can have a Tesla class that extends the Car class:

class Tesla extends Car {

}

The Tesla class inherits all the methods and properties of Car, including the constructor method.

We can create an instance of the Tesla class:

const myCar = new Tesla()

The original constructor in Car is executed, because Tesla does not have one of its own.

We can override the constructor() method in the Tesla class:

class Tesla extends Car {
  constructor() {
    console.log('This is a Tesla')
  }
}

and

const myCar = new Tesla()

will print This is a Tesla.

In the constructor() method we can call super() to invoke the same method in the parent class:

class Tesla extends Car {
  constructor() {
    super()
    console.log('This is a Tesla')
  }
}

Calling

const myCar = new Tesla()

will now run two console.log statements: first the one defined in the Car class constructor, then the one defined in the Tesla class constructor:

'This is a car'
'This is a Tesla'

Note that super() can only be called in the constructor, not in other methods.

And we can pass any parameters to the parent class if the constructor accepts them.

Lessons in this unit:

0: Introduction
1: Classes
2: Class methods
3: Private class properties
4: Constructors
5: ▶︎ Inheritance
6: Prototypes