Ereditarietà in Javascript - prototipazione non in definizione-parte?
-
05-07-2019 - |
Domanda
Attualmente sto passando da AS3 a JavaScript.
Ho ancora qualche problema con la comprensione dei concetti di eredità.
Quello che non capisco è perché il seguente codice non funziona correttamente:
Base = function () {
this.coolVar = "great";
}
SmallControl = function () {
// Inheritance:
this.prototype = new Base();
this.prototype.constructor = SmallControl;
this.prototype.init = function(aMap) {
console.log('init');
console.log('coolVar?: ' + this.coolVar);
}
}
var foo = new SmallControl();
//foo.init(); // --> TypeError: foo.init is not a function
foo.prototype.init(); // --> works
Se metto le definizioni del prototipo al di fuori della funzione "SmallControl", tutto funziona bene ... ma non lo capisco.
Soluzione
Penso che tu voglia qualcosa del genere:
// Create the super class
Base = function () {
this.coolVar = "great";
};
// Create the new class
SmallControl = function () {
};
// Set the prototype of SmallControl to be an instance of Base.
// This runs the Base constructor _immediately_ which sets up the variable
SmallControl.prototype = new Base();
// Add the init method to the SmallControl class
SmallControl.prototype.init = function(aMap) {
console.log('init');
console.log('coolVar?: ' + this.coolVar);
}
// Create an instance of SmallControl
var foo = new SmallControl();
foo.init();
Altri suggerimenti
prototype
è solo una proprietà significativa dei costruttori. Il prototipo effettivo dell'oggetto (che è accessibile in alcuni ambienti come proprietà __proto__
, ma questo non è portatile) è impostato per essere l'attributo prototype
del costruttore nel momento in cui l'oggetto è costruito. Le modifiche al prototipo del costruttore (aggiungendo proprietà al prototipo) si rifletteranno negli oggetti live, ma non se si imposta Constructor.prototype
su un oggetto completamente diverso.
Nel tuo costruttore, stai impostando l'attributo prototype
dell'oggetto costruito ( this
). Questo attributo non ha alcun significato speciale su qualcosa che non è una funzione di costruzione. Quando lo si imposta al di fuori della funzione, lo si imposta sulla funzione di costruzione.