0

I am just starting to learn prototype inheritance in JS and I would like the child object (def2) of my subclass object to inherit from superclass object's child object (def). The following code will explain what I mean:

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 

}
BlueChameleon
  • 924
  • 1
  • 10
  • 36

1 Answers1

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;

I suggest you read http://phrogz.net/JS/classes/OOPinJS2.html or a similar article

megawac
  • 10,953
  • 5
  • 40
  • 61