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

116
Vistas
Is it custom to create a static variable inside a function using `this.temp`?

I want to utilize a static variable in a function, i.e., a variable which adheres to the following requirements:

  1. It retains its value over different calls to that function
  2. It is known (accessible) only within the scope of that function

Here is a generic example of how I am achieving these requirements:

function func(state, input) {
    switch (state) {
    case 'x':
        this.temp = calc(input);
        return this.temp;
    case 'y':
        return this.temp;
    }
}

It works fine, but I'd like to know if it's a custom way, and if there's a better way (cleaner, simpler, better practice, etc).

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

0

That code doesn't meet your second criterion. Anything with access to the object this refers to has access to this.temp. (From the code in the question, this may even refer to the global object, in which case temp is a global accessible everywhere.)

If you need to have func store truly private information, the standard way to do that is to use a closure:

const func = (() => {
    let temp;
    return function func(state, input) {
        switch (state) {
        case 'x':
            temp = calc(input);
            return temp;
        case 'y':
            return temp;
        }
    };
})();

That runs an anonymous function when the code is run that returns the func to assign to the func constant, and uses the closure created by that call to give func a truly private temp variable.

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