Can a class extend multiple classes?

Question

In the context of this lesson, can a class extend multiple classes?

Answer

No, in JavaScript, a class cannot extend from multiple classes, which is also known as “multiple inheritance”.

In JavaScript, objects can only be associated with a single prototype, and extending multiple classes would mean that an object associates with multiple prototypes, which is not possible.

A workaround to this is that, if you need a class to inherit the attributes and methods of multiple classes, you might create a new class with those attributes and methods defined in it.

Because JavaScript is a prototype-based system not only can it handle multiple inheritance, but it can also handle partial inheritance, or even inherit partially from multiple other classes. The prototype allows you to specify exactly what you want to inherit and nothing more. On the other hand, if you plan to only use ES6 classes, then you cannot apply multiple (or partial) inheritances.

Here is one example of how you might do multiple inheritance:

class Person {
  constructor (first, last) {
    this.first = first
    this.last = last
  }

  fullName () {
    return this.first + ' ' + this.last
  }
}

class Employee {
  constructor (id, position) {
    this.id = id
    this.position = position
  }

  details () {
    return this.id + ' ' + this.position
  }
}

function EmployedPerson (first, last, employeeId, position) {
  Object.assign(
    this,
    new Person(first, last),
    new Employee(employeeId, position)
  )
}

EmployedPerson.prototype = {
  fullName: Person.prototype.fullName,
  details: Employee.prototype.details
}

const ep = new EmployedPerson('Jane', 'Doe', 1234, 'Developer')
console.log(ep.fullName()) // => Jane Doe
console.log(ep.details()) // => 1234 Developer