我是node中的n00b,发现util.inherits()
非常有用,除了它似乎替换了原始对象的整个原型(prototype)。例如:
var myClass = function(name){
this._name = name;
};
myClass.prototype = {
(...)
};
util.inherits(myClass, require('events').EventEmitter);
似乎抹去了我原来的原型(prototype)。
这给我带来了两个不便:
1 - 我必须在调用 inherits
,
var myClass = function(name){
this._name = name;
};
util.inherits(myClass, require('events').EventEmitter);
myClass.prototype.prop1 = function(){...};
myClass.prototype.prop2 = function(){...};
而且,最重要的是,我认为我不能从两个或更多不同的类继承。
谁能向我解释为什么这是有意义的,以及解决这个问题的好方法是什么?
谢谢
最佳答案
不你必须在util.inherits()
之后声明你的原型(prototype)是有意义的。我的猜测是 util.inherits
起源于一种仅供内部使用的方法,仅针对它最初打算用于的有限内部用例进行定制,在某些时候发布用于一般用途。 util
模块是用纯 JS 编写的,因此很容易实现您自己的 util.inherit
版本来保留您的原型(prototype)。这是原始 util.inherit
源代码:
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
至于多重继承,这将是一个更难解决的问题,因为 Javascript 的原型(prototype)继承根本不适合多重继承。每个实例只有一个内部 [[Prototype]]
属性,用于查找在实际实例中找不到的成员。您可以将两个单独的“父类”的原型(prototype)合并为一个原型(prototype),但随后您将失去对它们的父类的继承,并且您将失去更改的能力父原型(prototype),并让所有 child 都看到更改。
关于javascript - util.inherits - 替代或解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13474710/