Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda