I’ve been poking into some Node.js modules in the hopes of learning something I could have missed while creating a module with similar functionality. Then I came across this code from Hound:
function Hound() {
//why this?
events.EventEmitter.call(this)
}
//ok, so inheriting the EventEmitter
util.inherits(Hound, events.EventEmitter);
I know that the util.inherits() function from Node.js creates a new Parent instance as the prototype of the child constructor as stated in the docs:
The prototype of constructor will be set to a new object created from superConstructor.
So if our constructor is inheriting EventEmitter through util.inherits(), what is that code in the constructor for?
It’s just making your
Houndclass anEventEmitterobject.It gives your the EventEmitter instance methods to the class.
E.g.,
houndInstance.emit('something')Other objects that are listening to these events can then respond to them.
Per your comment:
In JavaScript,
.call(context)is a means of invoking a function in a specific context. In the example above, we’re just calling theSomeClassconstructor and passingthis(theHoundclass in this example) as the context.