I have been following Hands-On Node.js by by Manuel Teixiera and I stumbled upon this weird behaviour while going through the Event Emitter chapter.
The code suggested by the author consists of something like this:
var EventEmitter = require("events").EventEmitter;
var util = require ("util");
var MyClass = function() {};
util.inherits(MyClass, EventEmitter);
var instance = new MyClass();
instance.on("custom", function() {
console.log("Holo");
});
instance.emit("custom");*/
Which outputs "Holo" just fine. However, I have also read documentation and SO questions on the subject of how using new Function();
is an anti-pattern that flies in the face of javascript's intended use of prototypical inheritance. This article by David Walsh illustrates the difference between forcing classical inheritance on js and using its capabilities for prototypical inheritance.
So, I tried modify my code by re-writing it like so:
var EventEmitter = require("events").EventEmitter;
var clock = {};
util.inherits(clock, EventEmitter);
clock.on("custom", function(){
console.log("Holo");
});
clock.emit("custom");
I get an error saying TypeError: Object object has no method 'on'
. I don't understand why is this, since I have created the clock object with the util.inherit()
helper. The same code using var clock = Object.create(EventEmitter)
doesn't work either.
The only instance where I can get the code to work is this:
var EventEmitter = require("events").EventEmitter;
var util = require("util");
var clock = {};
util.inherits(clock, EventEmitter);
clock.prototype.on("custom", function(){
console.log("Holo");
});
clock.emit = function(){
clock.prototype.emit("custom");
}
clock.emit();
This outputs "Holo" just fine. The thing is, i don't understand why do I need to access the prototype to set an Event Listener or emit an Event when, supposedly, I made the clock
variable delegate it's methods to the EventEmitter
object, so they should work fine without the prototype notation.
Would you please help me?