views:

83

answers:

3

hi, how can i call super constructor from the inheriting object? for example, i have a simple animal 'class':

function Animal(legs) {
  this.legs = legs;
}

i want to create a 'Chimera' class that inherits from Animal but sets the number of legs to a random number (providing the maximum number of legs in the constructor. so far i have this:

function Chimera(maxLegs) {
    // generate [randLegs] maxed to maxLegs
    // call Animal's constructor with [randLegs]
}
Chimera.prototype = new Animal;
Chimera.prototype.constructor = Chimera;

how to call Animal's constructor? thanks

A: 

You should be able to do this:

new Animal();
kevin628
FYI, the reason you were downvoted is because, while this will call the Animal constructor, it will not call the animal constructor *on the current object*.
Chuck
Down voting seems a tad extreme. You could have just corrected me, rather than punishing me.
kevin628
+2  A: 

You can use the call method every function has:

function Chimera(maxLegs) {
   var randLegs = ...;
   Animal.call(this, randLegs);
}
sth
i get an error in the "Chimera.prototype = new Animal;" part because i think it calls Animal() without the parameters while instantiated
pistacchio
+3  A: 

I think what you want is similar to constructor chaining:

function Chimera(maxLegs) {
    // generate [randLegs] maxed to maxLegs
    // call Animal's constructor with [randLegs]
    Animal.call(this, randLegs);
}

Or you may consider Parasitic Inheritance

function Chimera(maxLegs) {

    // generate [randLegs] maxed to maxLegs
    // ...

    // call Animal's constructor with [randLegs]
    var that = new Animal(randLegs);

    // add new properties and methods to that
    // ...

    return that;
}
galambalazs