Can someone explain what util.inherits does in more laymans terms?
var util = require('util');
function Person() {
this.firstname = 'John';
this.lastname = 'Doe';
}
Person.prototype.greet = function() {
console.log('Hello ' + this.firstname + ' ' + this.lastname);
}
function Policeman() {
Person.call(this);
this.badgenumber = '1234';
}
util.inherits(Policeman, Person);
var officer = new Policeman();
officer.greet();
You can find the implementation of util.inherits
here:
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
It is essentially doing what you are describing (creating an instance of events.EventEmitter.prototype
and setting that as the prototype of MyStream
) along with attaching attaching events.EventEmitter
to MyStream.super_
.
The events.EventEmitter.call(this);
invokes the events.EventEmitter
constructor so that it gets executed whenever a new MyStream
is created. This is equivalent to calling super()
in other languages like Java.