Node.js — Extend Multiple Classes (Multi Inheritance)

Node.js benefits from new language features in JavaScript. The introduction of classes in JavaScript is a great step towards better extensibility.

You provide functionality in a base class, let other classes extend this base class, and use the given methods.

But how to extend multiple classes in Node.js? Read on to see how that works!

Node.js Series Overview

Install the “extends-classes” Package

By default, each class in Node.js can extend only a single class. That means, to inherit from multiple classes, you’d need to create a hierarchy of classes that extend each other.

But wait, there’s a simpler solution. The extends-classes package provides the convenient feature to extend multiple classes at once. At first, install the package to your project:

npm i extends-classes  

Extend Multiple Classes

Now that you installed the extends-classes package, go ahead and use it in your app.

The following code snippet is a preview of how Supercharge composes the base testing utility. Individual classes implement features like HTTP testing or faking data and the base test should extend all classes to make them available for the user.

const Many = require('extends-classes')  
const RenderViews = require('./concerns/render-views')  
const FakeData = require('./concerns/creates-fake-data')  
const MakeHttpRequests = require('./concerns/makes-http-requests')

class BaseTest extends Many(RenderViews, FakeData, MakeHttpRequests) {

  constructor () {
    super()

    this.initialize()
  }
}

module.exports = BaseTest  

Pass all classes as separate arguments to the import of extends-classes and it will do the inheritance. Notice that I’ve imported extends-classes as Many.

That’s it!

Enjoy coding & make it rock!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.