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

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

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 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