Javascript: prototyping and superconstructor

how can i call a super constructor from an 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 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 constructor with [randLegs] } Chimera.prototype = new Animal; Chimera.prototype.constructor = Chimera; 

How to call the constructor Animal? thanks

+4
source share
3 answers

I think what you want is like a chain of constructors :

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

Or you may consider Parasitic Inheritance

 function Chimera(maxLegs) { // generate [randLegs] maxed to maxLegs // ... // call Animal constructor with [randLegs] var that = new Animal(randLegs); // add new properties and methods to that // ... return that; } 
+4
source

You can use the call method for each function:

 function Chimera(maxLegs) { var randLegs = ...; Animal.call(this, randLegs); } 
+2
source

You should be able to do this:

 new Animal(); 
-2
source

All Articles