0

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

1
  • 1
    What is this during the call to func? How are you calling func? I strongly suspect what you're doing fails your second criterion. Commented Apr 26, 2022 at 9:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.