Apr 10th 2014How 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) {
  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'

Object.assign(myModule, EventEmitter.prototype);