0

我刚刚开始学习 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 

}
4

1 回答 1

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或类似的文章

于 2013-11-06T22:00:16.433 回答