Object.create 和继承

发布于 2024-12-18 06:28:24 字数 394 浏览 2 评论 0原文

以下示例中生成的对象之间有什么区别:

var EventEmitter = require('events').EventEmitter;

var oProto  = Object.create(EventEmitter.prototype);
var oProto2 = Object.create(oProto);

var oConstr  = Object.create(new EventEmitter);
var oConstr2 = Object.create(oConstr);

我认为 oConstroConstr2 将在 EventEmitter 构造函数中设置任何属性,但是还有其他有意义的区别吗?

What is the difference between the resulting objects in the following examples:

var EventEmitter = require('events').EventEmitter;

var oProto  = Object.create(EventEmitter.prototype);
var oProto2 = Object.create(oProto);

var oConstr  = Object.create(new EventEmitter);
var oConstr2 = Object.create(oConstr);

I suppose oConstr and oConstr2 will have any properties set in the EventEmitter constructor, but is there any other meaningful difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

断肠人 2024-12-25 06:28:24

您的代码具有误导性。当它不是构造函数时,您可以使用术语oConstr

oProto -> EventEmitter.prototype -> Object.prototype -> null
oProto2 -> oProto -> EventEmitter.prototype -> Object.prototype -> null

var temp = new EventEmitter;

oConstr -> temp -> EventEmitter.prototype -> Object.prototype -> null
oConstr2 -> oConstr -> etc

唯一的区别是 temp 不仅仅是一个继承自 EventEmitter 的对象,它还具有通过调用 EventEmitter.constructor.call(temp) 增强的自己的属性

我个人建议您使用 EventEmitter.prototype 并忽略 new EventEmitter

就我个人而言,我不会继承 EventEmitter我将其混合

Your code is misleading. you use the term oConstr when it's not a constructor function.

oProto -> EventEmitter.prototype -> Object.prototype -> null
oProto2 -> oProto -> EventEmitter.prototype -> Object.prototype -> null

var temp = new EventEmitter;

oConstr -> temp -> EventEmitter.prototype -> Object.prototype -> null
oConstr2 -> oConstr -> etc

The only difference is that temp is not just an object that inherits from EventEmitter it also has own properties augmented from the call to EventEmitter.constructor.call(temp).

I'd personally recommend you use EventEmitter.prototype and ignore new EventEmitter

Personally I don't ever inherit from EventEmitter, I mix it in

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文