在 the source对于 util.inherits
他们打电话object.create
创建一个新对象,其原型(prototype)是 super 构造函数的原型(prototype)。
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
这是为什么呢?为什么不这样做:
ctor.prototype = superCtr.prototype?
最佳答案
Why not just do: ctor.prototype = superCtr.prototype?
这意味着每当有人向 ctor.prototype
添加方法时,他们最终也会向 superCtr.prototype
添加方法,因为它们是同一个对象。
那太可怕了!这意味着如果你有例如http.IncomingMessage
继承自 EventEmitter
,那么 http.IncomingMessage.prototype
上的每个方法最终都会在 EventEmitter.prototype
上>。因此,所有 io.js 中的每个事件发射器都将具有与 HTTP 相关的方法!
相反,我们创建一个新对象,可以向其中添加特定于 ctor
实例的方法。由于我们确保该新对象是从 superCtor.prototype
中 Object.create
生成的,因此我们知道针对该对象的任何查找都将遵循 [[Prototype]] 链,并且从 superCtor.prototype
中查找方法,正如您在进行继承时所期望的那样。但它是一个新对象,有空间进行自定义,如您所愿。
关于javascript - 为什么 util.inherits 创建一个继承自 super 构造函数原型(prototype)的新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30688400/