2011-01-25 7 views
11

Quiero crear un objeto y ejecutar dos de sus métodos en la creación de objetos. Así que si mi objetivo es¿Cómo llamar a una función durante la construcción del objeto en Javascript?

function newObj(){ 
this.v1 = 10; 
this.v2 = 20; 
this.func1 = function(){ ....}; 
this.func2 = function(){...}; 
} 

y la llamada al objeto es

var temp = new newObj(); 

Quiero correr func1() y func2() sin llamarlos explícitamente en la variable TEMP, como temp.func1(). Quiero que se llamen cuando creo la nueva variable Object. Intenté poner this.func1() dentro de la declaración newObj, pero parece que no funciona.

Respuesta

1

Trate envolviéndolo en una función de auto invocación si nunca planea volver a utilizarlo, así:

function newObj(){ 
    this.v1 = 10; 
    this.v2 = 20; 
    this.func1val = (function(){ alert('called from c\'tor'); })(); 
    this.func2val = (function(){ return 2 + 1; })(); 
} 

var temp = new newObj(); 
alert('temp.func2val = ' + temp.func2val); 

DEMO

+0

Gracias, esto funcionó. El this.func1() no parece funcionar en Chrome para mí. – Parminder

+0

Sin embargo, esto se niega a funcionar – Parminder

+0

función highLightElement (elemento) { this.LEVEL = 128; this.ELEMENT = element; this.INTERVAL = 100; this.setTimeout (increaseYellow, INTERVAL); this.setYellowLevel = (function() { var hex = this.LEVEL.toString (16); element.style.backgroundColor = '#ffff' + hex; })(); this.newfunc = (function() {setTimeout (increaseYellow, INTERVAL);})(); this.increaseYellow = function() { LEVEL + = 10; if (NIVEL> 255) { NIVEL = 255; } setYellowLevel (ELEMENT, LEVEL); if (NIVEL <255) { setTimeout (increaseYellow, INTERVAL); } }; } – Parminder

6

Sólo tiene que llamar desde dentro de la misma que el constructor funciona bien: http://jsfiddle.net/yahavbr/tTf9d/

El código es:

function newObj(){ 
    this.v1 = 10; 
    this.v2 = 20; 
    this.func1 = function() { alert("func1"); }; 
    this.func2 = function() { alert("func2"); }; 

    this.func1(); 
    this.func2(); 
} 
4

Esto funciona para mí en Chrome:

function newObj(){ 
    this.v1 = 10; 
    this.v2 = 20; 
    this.func1 = function(){ this.v1 += 1; }; 
    this.func2 = function(){ alert(this.v1); }; 
    this.func1(); 
    this.func2(); 
} 
var obj = new newObj(); 
9

añadir sentencias método de invocación en el constructor:

 
function newObj(){ 
this.v1 = 10; 
this.v2 = 20; 
this.func1 = function(){ ....}; 
this.func2 = function(){...}; 
this.func1(); 
this.func2(); 
} 

creo que es la solución de sus necesidades.

0

Usando la función Auto invocación podemos llamar y también podemos compartir parámetro padre haciendo un poco de trabajo en torno variable pública var that = this;

function newObj(){ 

this.v1 = 10; // public variable 
this.v2 = 20; // public variable 
var that = this; // Allow access to parent function variable to inner function 
    (function(){ 
    // access parent function variable 
    // using 'that' ex: 
     that.v1 = 50; 
    //fun1code stuff 
    })(); 

    (function(){ 
    // access parent function variable 
    // using 'that' ex: 
    that.v2 = 60; 
    //fun2code stuff 
    })(); 
} 

var temp = new newObj(); 
console.log(temp.v1); // output 50 
console.log(temp.v2); // output 60 
0

Creo que tal vez necesita ser stresed que en JavaScript que necesita para definir el funciones del objeto (o métodos, si prefiere ese término) antes de llamarlos.

Por ejemplo, si desea llamar this.func1() durante la instanciación:

var new_object = new newObj(); // create/instantiate an object 

function newObj(){ 
    this.v1 = 10; 
    this.v2 = 20; 

    this.func1(); // <-- calling it here causes an error 

    this.func1 = function(){ ....}; 
    this.func2 = function(){ ....}; 
    this.func3 = function(){ ....}; 
} 

TypeError: this.func1 is not a function

Este es un problema que me encontré hace años cuando se trata de entender cómo hacer programación orientada a objetos en JS. Porque en otros lenguajes como Java o PHP, tienes una función/método constructor usualmente en la parte superior de tu clase, y debajo de ti escribes tus otras funciones/métodos.

Así que parece lógico escribir su clase así: 1) defina las propiedades de su objeto, y luego 2) enumere las cosas que desea hacer cuando se crea una instancia del objeto, y luego 3) enumere las otras funciones/métodos de clase .

PERO NO !!

Con JavaScript, debe definir las funciones del objeto antes de llamarlas.

Así que si usted desea llamar dos métodos en la creación de objetos/instancias, digamos this.func1() y this.func2(), primero definir todo en su clase y al final lugar el método llama:

var new_object = new newObj(); // create/instantiate an object 

function newObj(){ 
    this.v1 = 10; 
    this.v2 = 20; 

    this.func1 = function(){ ....}; 
    this.func2 = function(){ ....}; 
    this.func3 = function(){ ....}; 

    this.func1(); // <-- it works here! 
    this.func2(); // <-- it works here! 
} 

Si Quería que tu código se organizara con un método constructor colocado en la parte superior de otros métodos de clase (como se mencionó anteriormente, cómo PHP y Java lo hacen), entonces podrías hacer un pequeño método this._constructor() y colocar cosas allí, y llamarlo al final de su clase:

function newObj(){ 
    this.v1 = 10; 
    this.v2 = 20; 

    this._constructor = function(){ // do constructor things here 
    this.func1(); 
    this.func2(); 
    } 
    this.func1 = function(){ ....}; 
    this.func2 = function(){ ....}; 
    this.func3 = function(){ ....}; 

    this._constructor(); // call just one method here, nice and tidy 
} 

Algunos pueden decir que es un poco redundante, pero lo ayuda a que el flujo de trabajo más rápido ... :)

Sólo para que conste, si desea pasar un argumento al crear/crear instancias de un objeto, es decir quería tener la opción de configurar this.v1, entonces usted podría hacerlo así:

function newObj(set_v1){ 
    this.v1 = 10; 
    this.v2 = 20; 

    this._constructor = function(set_v1){ // do constructor things here 
    if (set_v1 != undefined){ // you can come up with a better condition here 
     this.v1 = set_v1; 
    } 
    this.func1(); 
    this.func2(); 
    } 
    this.func1 = function(){ ....}; 
    this.func2 = function(){ ....}; 
    this.func3 = function(){ ....}; 

    this._constructor(set_v1); // call the constructor here and pass the argument 
} 
Cuestiones relacionadas