Pregunta

Actualmente estoy cambiando de AS3 a JavaScript.
Todavía tengo algunos problemas para entender los conceptos de herencia.
Lo que no entiendo es por qué el siguiente código no funciona correctamente:

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

Si pongo las definiciones de prototipo fuera del " SmallControl " -Función todo funciona bien ... pero no lo entiendo.

¿Fue útil?

Solución

Creo que quieres algo como esto:

// 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(); 

Otros consejos

prototype es solo una propiedad significativa de los constructores. El prototipo real del objeto (al que se puede acceder en algunos entornos como la propiedad __proto__ , pero no es portátil) se configura como el atributo prototype del constructor en el momento en que el objeto está construido. Los cambios en el prototipo del constructor (agregando propiedades al prototipo) se reflejarán en los objetos vivos, pero no si configura Constructor.prototype para que sea un objeto completamente diferente.

En su constructor, está configurando el atributo prototype del objeto construido ( this ). Este atributo no tiene un significado especial en algo que no es una función constructora. Cuando lo establece fuera de la función, lo establece en la función de constructor.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top