本文介绍了来自多个对象的javascript继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太熟悉javascript继承,我试图让一个对象从另一个继承,并定义自己的方法:

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();

然而,第二个覆盖第一个( FooB.prototype = new Foo()被取消)。有没有办法解决这个问题,或者我的方向是错误的?

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.

推荐答案

每个对象只能有一个原型,所以如果你想在继承(复制)它之后添加到原型,你必须扩展它而不是分配一个新的原型。示例:

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:

function Foo() {}

Foo.prototype = {
    x: function(){ alert('x'); },
    y: function(){ alert('y'); }
};

function Foo2() {}

Foo2.prototype = new Foo();
Foo2.prototype.z = function() { alert('z'); };

var a = new Foo();
a.x();
a.y();
var b = new Foo2();
b.x();
b.y();
b.z();

这篇关于来自多个对象的javascript继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:33