1

I'm learning Node.js and have some confusion about customized EventEmitter. Here's the code:

var events = require("events");
function MyEmitter (name){
        this.name = name;
//      events.EventEmitter.call(this);
        this.emitEvent = function(){
                this.emit("Event1");
        }
}
//MyEmitter.prototype.__proto__ = events.EventEmitter.prototype;
MyEmitter.prototype         = events.EventEmitter.prototype;

function foo(){
        console.log("callback: " + this.name);
}

var obj = new MyEmitter("MyEmitter");
obj.on("Event1", foo);
obj.emitEvent();

There's two similar lines to inherit from EventEmitter;

//MyEmitter.prototype.__proto__ = events.EventEmitter.prototype;
    MyEmitter.prototype         = events.EventEmitter.prototype;

It seems both of these two expressions will work. And I saw "The proto property is deprecated" from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

Besides, if I comment out the

//      events.EventEmitter.call(this);

The code will also work.

I heard that call() is used as a constructor of EventEmitter,

//MyEmitter.prototype.__proto__ = events.EventEmitter.prototype;

and this line is used to copy all of the EventEmitter properties to the Door object.

So why do we have to copy the properties twice?

Could anyone tell me what's the difference between these expression?

  • http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks Oct 15 '14 at 15:55
  • 1
    Possibly related: [How should you inherit from EventEmitter in node?](http://stackoverflow.com/questions/20201017/how-should-you-inherit-from-eventemitter-in-node) – apsillers Oct 15 '14 at 15:55
  • Definitely related: [Prototypal inheritance and new keyword](http://stackoverflow.com/questions/10393869/prototypal-inheritance-and-new-keyword) – apsillers Oct 15 '14 at 15:59

1 Answers1

0
MyEmitter.prototype         = events.EventEmitter.prototype;

You just assigned your class to have the same prototype as EventEmitter.

That means that anything you add to your prototype will actually be added to EventEmitted.prototype.

That's a very bad idea.

The correct solution is to call Object.create() to create a new object that inherits its prototype, as I explain in my blog.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    It should be noted that the solution used throughout node core and many modules in npm is to use `util.inherits()`. – mscdex Oct 15 '14 at 16:01
  • @mscdex: Which does exactly what my blog post describes. – SLaks Oct 15 '14 at 16:07
  • 1
    That may be, but IMHO having this abstraction is nice in case of improved inheritance methods or possible language-related deprecation. Also it's shorter and a bit clearer as to what's happening when visually scanning code. – mscdex Oct 15 '14 at 16:22
  • Yes, but it's also important to understand how it works. – SLaks Oct 15 '14 at 16:48