Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!