Max SchmittMS
10th April 2014

How to make an object inherit from a class in JavaScript

In node.js, it's really easy to make on "class" inherit from another "class". Many node-modules make use of util.inherits for this.

Classical inheritance with JavaScript (class-class)

If you have two "classes", you can make one inherit from another by doing the following:

var util = require('util')
var EventEmitter = require('events').EventEmitter
var Person = function(name) {
EventEmitter.call(this)
this.name = name
}
util.inherits(Person, EventEmitter)

Now every Person object is also an EventEmitter.

Class-object inheritance in JavaScript

In JavaScript it's not uncommon to work without class-like objects, but you might want your object to inherit functionality from a class-like object. It works very similarly:

var EventEmitter = require('events').EventEmitter
var person = {
name: 'Max'
}
EventEmitter.call(myModule)
Object.assign(myModule, EventEmitter.prototype)
Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.