2012-02-14 18 views
15

que estaba buscando un constructor o una función init para la siguiente situación:Constructor o función init para un objeto

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 
}; 
Abc.prototype.init = function(){ 
    // Perform some operation 
}; 

//Creating a new Abc object using Constructor. 

var currentAbc = new Abc(obj,obj); 

//currently I write this statement: 
currentAbc.init(); 

¿Hay una manera de llamar a la función init cuando se inicializa nuevo objeto?

+1

Colóquelo en el contructor. –

Respuesta

17

Usted puede simplemente llamar init() de la función constructora

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 
    this.init(); 
}; 

Aquí es un violín que demuestra: http://jsfiddle.net/CHvFk/

+3

El inconveniente que veo en este patrón es que init es público. Se puede llamar como a.init(). Por lo general, las funciones de inicio son privadas. Por lo tanto, podría ser bueno definirlo en el constructor. Consulte [actualización de violín] (http://jsfiddle.net/CHvFk/126/) – Buzut

11

Tal vez algo como esto?

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 
    this.init = function(){ 
     // Do things here. 
    } 
    this.init(); 
}; 
var currentAbc = new Abc(obj,obj); 
+2

Esto es correcto, debe llamar a la función init() DESPUÉS de definirla. – Wes

-4

por qué no poner las cosas en función init a cunstructor, así:

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 

    // Perform some operation 

}; 
+1

¿Por qué se están utilizando las funciones? Para reducir la redundancia y la modularidad de su código. Es por eso que lo quiero como una función. – emphaticsunshine

4

si su método init debe permanecer privada:

var Abc = function(aProperty,bProperty){ 
    function privateInit(){ console.log(this.aProperty);} 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 

    privateInit.apply(this); 
}; 

me gusta esto más.

0

¿Qué tal esto?

var Abc = function(aProperty,bProperty){ 
    this.aProperty = aProperty; 
    this.bProperty = bProperty; 

    //init 
    (function() { 
     // Perform some operation 
    }.call(this)); 
}; 
var currentAbc = new Abc(obj,obj); 
Cuestiones relacionadas