The util
Module provides the util.inherits()
method to allow you to create objects that inherit the prototype
methods from another object. When you create a new object, the prototype
methods are automatically used. You have already seen this in a few examples in this book—for example, when implementing your own custom Readable
and Writable
streams.
The following is the syntax of the util.inherits()
method:
util.inherits(constructor, superConstructor)
The prototype constructor
is set to the prototype superConstructor
and is executed when a new object is created. You can access superConstructor
from your custom object constructor by using that constructor.super_
property.
Listing 10.2 illustrates using inherits()
to inherit the events.EventEmitter
object constructor to create a Writable
stream. Notice that on line 11 the object is an instance of events.EventEmitter
. Also notice that on line 12 the Writer.super_
value is eventsEmitter
. Figure 10.2 shows the results of Listing 10.2.
01 var util = require("util");
02 var events = require("events");
03 function Writer() {
04 events.EventEmitter.call(this);
05 }
06 util.inherits(Writer, events.EventEmitter);
07 Writer.prototype.write = function(data) {
08 this.emit("data", data);
09 };
10 var w = new Writer();
11 console.log(w instanceof events.EventEmitter);
12 console.log(Writer.super_ === events.EventEmitter);
13 w.on("data", function(data) {
14 console.log('Received data: "' + data + '"'),
15 });
16 w.write("Some Data!");