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
}
Gracias, esto funcionó. El this.func1() no parece funcionar en Chrome para mí. – Parminder
Sin embargo, esto se niega a funcionar – Parminder
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