0

I'm reading this article on extending the EventEmitter class in node and there's a small part that I don't understand:

Door.prototype.__proto__ = events.EventEmitter.prototype;

I've looked up several articles on how this is supposed to work but really don't understand it. I know that alternatively, I could also use util.inherits but I'm trying to understand what happens in the line above.

I'd also like to know if doing this would have the same result as using __proto__:

Door.prototype = Object.create(EventEmitter.prototype);
//or
Door.prototype = new EventEmitter(); // I know this also calls constructor

So, what is the difference about these three methods, and how does __proto__ work?

EDIT:

So I looked at the links that were posted. I understand that prototype is basically used to build __proto__ which is then used in the lookup chain to resolve methods. The article I linked to also says that this line copies all the EventEmitter properties to the door object:

Door.prototype.__proto__ = events.EventEmitter.prototype;

Now my question, which might not have been clear earlier is: if the point of the line above, is copying the properties of the EventEmitter to the door object, I think the same could be achieved by doing:

Door.prototype = new EventEmitter();
blop
  • 31
  • 1
  • 7
  • 2
    Possible duplicate of [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – Robert Rossmann Feb 06 '16 at 12:04
  • This question might also be helpful (has link to a nice article) http://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript – grabantot Feb 06 '16 at 12:30

1 Answers1

0

This is all about what objects have access to and why.

We need to understand __proto__ vs prototype. I will refer you to this question and answer to help you understand the two. __proto__ VS. prototype in JavaScript

The line of code you are looking at is a constructor that is inheriting from the EventEmitter prototype. This creates a chain like system to include methods from multiple constructor functions.

Door.prototype.open = function(){ ... open something... };
Door.prototype.__proto__ = events.EventEmitter.prototype;
var myDoor = new Door;

The object myDoor will have the method open and all methods from the EventEmitter prototype.

Community
  • 1
  • 1
Michael Warner
  • 3,879
  • 3
  • 21
  • 45
  • So if I undertand correctly, using `__proto__` we can change `Door.prototype` after it has been intiated. But couldn't the same thing be achieved by using `Door.prototype = Object.create(EventEmitter.prototype);`? – blop Feb 06 '16 at 17:29