tco*_*ooc 1 javascript oop multiple-inheritance prototypal-inheritance
我不太熟悉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();
Run Code Online (Sandbox Code Playgroud)
但是,第二个会覆盖第一个(FooB.prototype = new Foo() is cancelled out).有什么方法可以解决这个问题,还是我朝错误的方向走?
在此先感谢,抱歉任何不好的术语.
每个对象只能有一个原型,因此如果要在继承(复制)后添加到原型,则必须扩展它而不是分配新的原型.例:
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();
Run Code Online (Sandbox Code Playgroud)