原型上子对象的Javascript继承

Javascript inheritence of child object on prototype

本文关键字:Javascript 继承 对象 原型      更新时间:2023-09-26

我刚刚开始学习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 
}
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 或类似的文章