Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
How to refer to a state for a javascript function without refering to its name explicitely

How can I set state https://jsfiddle.net/7q1530sp/10/ doesn't work

function o(){
 this.state = true;
}

o.f = function() {
  alert(this.state);
}
o.state = false;
o();
o.f();

instead of refering to o explicitely within its function https://jsfiddle.net/7q1530sp/9/

function o(){
 o.state = true;
}

o.f = function() {
  alert(this.state);
}
o.state = false;
o();
o.f();

Is there a way to refer to o without using its name ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Usually, to initialize a function you should use NEW before executing it, example:

var my = new fn()

However, I would advise you to opt for prototypes:

In addition to being comfortable to use, in case of complex projects, they will also allow you to divide your project into multiple files while keeping the code clean and tidy!

I leave you a small example on how prototypes are used:

var my = function(){}
my.prototype.test = true;
my.prototype.run = function(){
    console.log(this.test)
}

var w = new my();
w.run();
w.test = false;
w.run();

Update: Of course, you could also globally change the value of the variable like so:

var my = function(){}
my.prototype.test = true;
my.prototype.run = function(){
    console.log(this.test)
}

new my().run();
my.prototype.test = false;
new my().run();

Output:

true
false
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda