javascript从多个对象继承
我不太熟悉 javascript 继承,我试图让一个对象从另一个对象继承,并定义它自己的方法:
function Foo() {}
Foo.prototype = {
getColor: function () {return this.color;},
};
function FooB() {}
FooB.prototype = new Foo();
FooB.prototype = {
/* other methods here */
};
var x = new FooB().getColor();
但是,第二个对象覆盖第一个对象(FooB.prototype = new Foo( ) 被取消
)。有什么办法可以解决这个问题,还是我走错了方向?
预先感谢,对于任何不好的术语表示抱歉。
I'm not very well aquainted with javascript inheritance, and I'm trying to make one object inherit from another, and define its own methods:
function Foo() {}
Foo.prototype = {
getColor: function () {return this.color;},
};
function FooB() {}
FooB.prototype = new Foo();
FooB.prototype = {
/* other methods here */
};
var x = new FooB().getColor();
However, the second one overwrites the first one(FooB.prototype = new Foo() is cancelled out
). Is there any way to fix this problem, or am I going in the wrong direction?
Thanks in advance, sorry for any bad terminology.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每个对象只能有一个原型,所以如果你想在继承(复制)它之后添加原型,你必须扩展它而不是分配一个新的原型。例子:
Each object can only have one prototype, so if you want to add to the prototype after inheriting (copying) it, you have to expand it instead of assigning a new prototype. Example:
一种解决方案是:
更新:关于使用现有对象进行扩展。您始终可以将一个对象的现有属性复制到另一个对象:
只要
proto
是一个“普通”对象(即不从另一个对象继承)就可以了。否则,您可能需要添加 if(proto.hasOwnProperty(prop)) 来仅添加非继承属性。One solution would be:
Update: Regarding expanding with an existing object. You can always copy the existing properties of one object to another one:
As long as
proto
is a "plain" object (i.e. that does not inherit from another object) it is fine. Otherwise you might want to addif(proto.hasOwnProperty(prop))
to only add non-inherited properties.您可以使用
extend
函数将新成员复制到原型对象。延长
You can use an
extend
function which copies the new members to the prototype object.extend