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

122
Vistas
JavaScript local static varible like in C/C++

Below is some code demostrates static local variable in C/C++. Counter would be added for each time when btnTestOnclick is called -- counter can be accumulated.

void btnTestOnclick()
{
    static int counter = 0;
    counter++;
}

But in the below JS code,

function btnTestOnclick() {

        class temp{
        static counter=0;
        };
        console.log(temp.counter);
        temp.counter+=1;
}

This temp.counter can't be accumulated, every time it's 0. I know moving the temp class out of the function would work, but this class is supposed to logically be local since only btnTestOnclick would use it.

How do you think about it?

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

0

You need a closure where the persistent variable only visible to btnTestOnclick is created. Use an immediately-invoked function expression.

const btnTestOnclick = (() => {
  let counter = 0;
  return () => {
    counter++;
    // do other stuff with counter?
  };
})();

That said, personally, I consider IIFEs to be slightly outdated nowadays. If the section of code you're writing this in is such that you're afraid that adding another variable to its scope (counter) would make things more confusing than would be ideal, it's probably time to extract some of that code into a standalone module.

let counter = 0;
export const btnTestOnclick = () => {
  counter++;
  // do other stuff with counter?
};

where the above file contains nothing else (and thus counter is clearly scoped only to the exported btnTestOnclick)

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