问题描述
我正在查看有关node.js事件模块的这篇文章:
I am looking at this article regarding the node.js events module:
在其中有这样的代码:
Door.prototype.__proto__ = events.EventEmitter.prototype;
据说将Door对象的原型设置为event.EventEmitter的原型。
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 protobut 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;
推荐答案
此代码
Door.prototype.__proto__ = events.EventEmitter.prototype
使 Door.prototype
继承自 events.EventEmitter.prototype
。
所以原型链就像
doorInstance -> Door.prototype -> events.EventEmitter.prototype
此方法类似于
Door.prototype = Object.create(events.EventEmitter.prototype)
不同之处在于修改[[Prototype]]不会创建新对象,但会对性能产生很大的负面影响。
The difference is that modifying the [[Prototype]] does not create a new object, but it has a great negative impact on performance.
,此代码
Door.prototype = events.EventEmitter.prototype
使门
实例直接从 events.EventEmitter.prototype $ c $继承c>。
也就是说,您将无法在 Door.prototype
中添加特定方法而不会造成污染 events.EventEmitter.prototype
。
That is, you won't be able to add specific methods in Door.prototype
without polluting events.EventEmitter.prototype
.
这篇关于设置Object.prototype .__ proto__而不仅仅是Object.prototype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!