Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

javascript - Setting Object.prototype.__proto__ instead of just Object.prototype?

I am looking at this article regarding the node.js events module:

http://www.sitepoint.com/nodejs-events-and-eventemitter/

And in it there is this code:

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

Which supposedly sets the prototype of the Door object to the prototype of the event.EventEmitter.

I believe I know what is the difference between prototype and proto but this code completely confuses me. So my questions is whether instead of using:

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

The author of the article did not just use this line of code:

Door.prototype= events.EventEmitter.prototype;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This code

Door.prototype.__proto__ = events.EventEmitter.prototype

makes Door.prototype inherit from events.EventEmitter.prototype.

So the prototype chain will be like

doorInstance -> Door.prototype -> events.EventEmitter.prototype

This approach is similar to

Door.prototype = Object.create(events.EventEmitter.prototype)

The difference is that modifying the [[Prototype]] does not create a new object, but it has a great negative impact on performance.

Instead, this code

Door.prototype = events.EventEmitter.prototype

makes Door instances inherit directly from events.EventEmitter.prototype.

That is, you won't be able to add specific methods in Door.prototype without polluting events.EventEmitter.prototype.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...