Javascript: prototypal inherence and super constructor
-
29-09-2019 - |
Question
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
Solution
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;
}
OTHER TIPS
You can use the call
method every function has:
function Chimera(maxLegs) {
var randLegs = ...;
Animal.call(this, randLegs);
}
You should be able to do this:
new Animal();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow