简体   繁体   English

Object.create和继承

[英]Object.create and inheritance

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? 我想oConstroConstr2将在EventEmitter构造函数中设置任何属性,但是还有其他有意义的区别吗?

Your code is misleading. 您的代码具有误导性。 you use the term oConstr when it's not a constructor function. 当它不是构造函数时,可以使用术语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

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) . 唯一的区别是temp不仅是从EventEmitter继承的对象,它还具有对EventEmitter.constructor.call(temp)的调用所增强的自身属性。

I'd personally recommend you use EventEmitter.prototype and ignore new EventEmitter 我个人建议您使用EventEmitter.prototype并忽略new EventEmitter

Personally I don't ever inherit from EventEmitter , I mix it in 我个人从不从EventEmitter继承, 我将其混入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM