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?
CodePudding user response:
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
)