设置Object.prototype .__ proto__而不仅仅是Object.prototype? [英] Setting Object.prototype.__proto__ instead of just Object.prototype?

查看:429
本文介绍了设置Object.prototype .__ proto__而不仅仅是Object.prototype?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看有关node.js事件模块的这篇文章:

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

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

在其中有这样的代码:

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.

我相信我知道原型之间的区别是什么和 proto
但这段代码完全让我困惑。所以我的问题是代替使用:

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;


推荐答案

此代码

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

也就是说,您将无法在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆