我刚开始学习JS中的原型继承,我希望我的子类对象的子对象( def2 )继承自超类对象的子对象( def )。以下代码将解释我的意思:
function Animal(name)
{
this.name = name;
this.def = {
FieldA: 'aaa',
FieldB: 'bbb'
}
}
function Rabbit(name, category)
{
Animal.apply(this, arguments);
this.def2 = { };
this.def2.prototype = Animal.def;
alert(this.def2.FieldA); // this is undefined
}
答案 0 :(得分:1)
function Rabbit(name, category) {
Animal.apply(this, arguments);
this.def2 = clone(this.def); //where clone is a function similar to http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object#answer-122190
alert(this.def.FieldA); // this is 'aaa'
}
Rabbit.prototype = new Animal(); //inherit Animal
Rabbit.prototype.constructor = Rabbit;
我建议你阅读http://phrogz.net/JS/classes/OOPinJS2.html或类似的文章