Object.create 和继承
以下示例中生成的对象之间有什么区别:
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);
我认为 oConstr
和 oConstr2
将在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码具有误导性。当它不是构造函数时,您可以使用术语
oConstr
。唯一的区别是
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.The only difference is that
temp
is not just an object that inherits fromEventEmitter
it also has own properties augmented from the call toEventEmitter.constructor.call(temp)
.I'd personally recommend you use
EventEmitter.prototype
and ignorenew EventEmitter
Personally I don't ever inherit from
EventEmitter
, I mix it in