javascript util.inherits - 替代或解决方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13474710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
util.inherits - alternative or workaround
提问by André Al?ada Padez
I am a n00b in node, and find util.inherits()
very useful, except for the fact that it seems to replace the entire prototype of the original object. For instance:
我是 node 中的 n00b,发现util.inherits()
非常有用,除了它似乎替换了原始对象的整个原型。例如:
var myClass = function(name){
this._name = name;
};
myClass.prototype = {
(...)
};
util.inherits(myClass, require('events').EventEmitter);
seems to erase my original prototype.
似乎抹去了我原来的原型。
That brings me two inconveniences:
1 - I have to declare add properties to my prototype after calling inherits
,
这给我带来了两个不便:
1 - 我必须在调用后向我的原型声明添加属性inherits
,
var myClass = function(name){
this._name = name;
};
util.inherits(myClass, require('events').EventEmitter);
myClass.prototype.prop1 = function(){...};
myClass.prototype.prop2 = function(){...};
and, most important, i think i cannot inherit from two or more different classes.
而且,最重要的是,我认为我不能从两个或更多不同的类继承。
Can anyone explain to me why this makes sense and what would be a good way to work around this?
任何人都可以向我解释为什么这是有道理的以及解决这个问题的好方法是什么?
Thanks
谢谢
采纳答案by LifeQuery
As of node version 5.0.0, util.inheritshas been changed to support the behaviour you are looking for using the setPrototypeOfmethod:
从节点版本 5.0.0 开始,util.inherits已更改为支持您使用setPrototypeOf方法寻找的行为:
FirstBase.js
FirstBase.js
function FirstBase(firstBaseProp){
this.firstBaseProp = firstBaseProp;
}
FirstBase.prototype.getFirstBaseProp = function(){
return this.firstBaseProp;
};
module.exports = FirstBase;
SecondBase.js
第二库.js
var FirstBase = require('./FirstBase.js'),
util = require('util');
function SecondBase(firstBaseProp, secondBaseProp){
this.secondBaseProp = secondBaseProp;
SecondBase.super_.apply(this, arguments);
}
SecondBase.prototype.getSecondBaseProp = function(){
return this.secondBaseProp;
};
util.inherits(SecondBase, FirstBase);
module.exports = SecondBase;
ThirdBase.js
第三库.js
var SecondBase = require('./SecondBase.js'),
util = require('util');
function ThirdBase(firstBaseProp, secondBaseProp, thirdBaseProp){
this.thirdBaseProp = thirdBaseProp;
ThirdBase.super_.apply(this, arguments);
}
ThirdBase.prototype.getThirdBase = function(){
return this.thirdBaseProp;
};
util.inherits(ThirdBase, SecondBase);
module.exports = ThirdBase;
instance.js
实例.js
var ThirdBase = require('./ThirdBase.js');
var instance = new ThirdBase('first', 'second', 'third');
// With node < 5.0.0 (Object.create)
console.log(instance.getFirstBaseProp()); // first
console.log(instance.getSecondBaseProp()); // undefined
console.log(instance.getThirdBase()); // undefined
// With node >= 5.0.0 (Object.setPrototypeOf)
console.log(instance.getFirstBaseProp()); // first
console.log(instance.getSecondBaseProp()); // second
console.log(instance.getThirdBase()); // third
If you're running an older version of node that supports setPrototypeOf
(0.12.x does), you can just export
util.inheritsand use it as an internal utility function.
如果您正在运行支持setPrototypeOf
(0.12.x支持)的旧版本节点,则可以仅使用export
util.inherits并将其用作内部实用程序函数。
回答by lanzz
It does notmake sense that you have to declare your prototype after util.inherits()
. My guess is util.inherits
originated as an internal-use-only method, tailored only for the limited internal use-cases it was initially intended for, which at some point got published for general usage. The util
module is written in pure JS, so it is very easy to implement your own version of util.inherit
that preserves your prototype. Here's the original util.inherit
source:
必须在 之后声明原型是没有意义的util.inherits()
。我的猜测util.inherits
起源于一种仅供内部使用的方法,仅针对它最初打算用于的有限内部用例进行定制,在某些时候发布用于一般用途。该util
模块是用纯 JS 编写的,因此很容易实现您自己的util.inherit
保留原型的版本。这是原始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
}
});
};
As for the multiple inheritance, that's going to be a much more difficult problem to tackle, as Javascript's prototype inheritance is not really suited for multiple inheritance at all. Each instance has only a single internal [[Prototype]]
property, which is used to look up members that are not found in the actual instance. You couldmerge the prototypes of two separate "parent classes" into a single prototype, but you will then lose the inheritance to theirparents, and you will lose the ability to change the parent prototype and have all children see the change.
至于多重继承,这将是一个更难解决的问题,因为Javascript的原型继承根本不适合多重继承。每个实例只有一个内部[[Prototype]]
属性,用于查找在实际实例中找不到的成员。你可以两个独立的“父类”的原型合并成一个单一的原型,但随后你就失去了继承他们的父母,你会失去更改父原型,并拥有所有的孩子看到了变化的能力。
回答by Delio
You should first inherit, after the function definition, and then implement your object. Also don't forget to call the superclass constructor in your class's constructor.
您应该首先继承,在函数定义之后,然后实现您的对象。另外不要忘记在类的构造函数中调用超类构造函数。
Function A(y){
this.y = x;
}
Function B(x,y){
this.x = x;
A.call(this,y);
}
util.inherits(B,A);
B.prototype.mythodA = function() {
//do something
}
回答by jedmao
I very much wanted the same thing and was unhappy with extend, so I created this extension to the already useful util.inherits
method:
我非常想要同样的东西并且对扩展不满意,所以我为已经有用的util.inherits
方法创建了这个扩展:
var util = require('util');
module.exports = {
inherits : function(sub, sup, proto) {
util.inherits(sub, sup);
if (typeof proto !== 'undefined') {
Object.keys(proto).forEach(function(key) {
sub.prototype[key] = proto[key];
});
}
}
};
I put this in my project's ./util/index.js
and then do this to use it:
我把它放在我的项目中./util/index.js
,然后这样做来使用它:
var EventEmitter = require('events').EventEmitter;
var util = require('./util');
function Foo() {
EventEmitter.call(this);
}
util.inherits(Foo, EventEmitter, {
bar : function(){
console.log(this instanceof EventEmitter); // true
}
});
Maybe I'll publish this if I find it's robust and useful more and more. I just barely implemented it myself, so I'm giving it a test run.
如果我发现它越来越强大和有用,也许我会发布它。我自己只是勉强实现了它,所以我正在对其进行测试。
Let me know what you think!
让我知道你的想法!
NOTE: This doesoverride methods on either of the classes with the ones defined in the proto hash at the end. Just be aware of that.
注意:这确实覆盖了任何一个类上的方法,最后是原始哈希中定义的方法。请注意这一点。