Merc Merc - 5 months ago 3x
Javascript Question

How does the inherits function work in Node.js?

This is the inherits function in node.js:

exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true

Can somebody please give me the "big picture" of how this function works?
I am not 100% sure I get Object.create , and... well I am confused!

Any help/pointers will be greatly appreciated...


var Parent = function () {
  this.isParent = true;

Parent.prototype.doSomething = function () {
  return 42;

var Child = function () {
  this.isChild = true;
util.inherits(Child, Parent);

var c = new Child;

It simply makes sure that Child.prototype inherits from Parent.prototype properly. It also set's the constructor property Child.prototype to the correct value.

Make sure to call util.inherits directly after your Child declaration.