'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:
- It retains its value over different calls to that function
- 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).
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
