Javascript: ereditarietà prototipale e costruttore di eccellente
-
29-09-2019 - |
Domanda
Come posso chiamare super-costruttore dall'oggetto ereditare? per esempio, ho un semplice animale 'classe':
function Animal(legs) {
this.legs = legs;
}
Voglio creare un 'Chimera' classe che eredita da animali, ma imposta il numero di gambe per un numero casuale (che fornisce il numero massimo di gambe nel costruttore finora ho questo:.
function Chimera(maxLegs) {
// generate [randLegs] maxed to maxLegs
// call Animal's constructor with [randLegs]
}
Chimera.prototype = new Animal;
Chimera.prototype.constructor = Chimera;
come chiamare il costruttore di animali? grazie
Soluzione
Credo che ciò che si vuole è simile a costruttore concatenamento :
function Chimera(maxLegs) {
// generate [randLegs] maxed to maxLegs
// call Animal's constructor with [randLegs]
Animal.call(this, randLegs);
}
Oppure si può prendere in considerazione Parassita 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;
}
Altri suggerimenti
È possibile utilizzare il metodo call
ogni funzione ha:
function Chimera(maxLegs) {
var randLegs = ...;
Animal.call(this, randLegs);
}
Si dovrebbe essere in grado di fare questo:
new Animal();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow