I am learning node.js. On the nodejs api website there is a piece of code that I don't really get. The link is here
var util = require("util");
var events = require("events");
function MyStream() {
events.EventEmitter.call(this);
}
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
}
var stream = new MyStream();
console.log(stream instanceof events.EventEmitter); // true
console.log(MyStream.super_ === events.EventEmitter); // true
stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"
so the confusing part is
events.EventEmitter.call(this);
What does it do here?
MyStream
is a new object declaration that inherits behaviors from events.EventEmitter
as can be seen from this line where the inheritance is configured:
util.inherits(MyStream, events.EventEmitter);
So, when the MyStream
constructor is invoked usually via something like var stream = new MyStream();
, it needs to also invoke the constructor of the object that it inherits from so the parent object can initialize itself properly. That's what this line is:
events.EventEmitter.call(this);
events.EventEmitter
is the constructor of the object that MyStream
inherits from. events.EventEmitter.call(this)
instructs Javascript to call that constructor with the this
pointer set to this
object.
If you need more help with understanding .call()
, you can read this MDN reference.