I'm trying to call a function without re-initializing (hope I used the correct word here) it every time I call it. So the first time it gets called, it should initialize, but after its initialized, it should just use that reference.
Here's the code I'm trying to do it with.
console.clear();
function mainFunction(e) {
var index = 0;
function subFunction() {
console.log(index++);
}
return subFunction();
}
window.addEventListener('click', mainFunction)
index
should increase by one every time mainFunction
gets called. The obvious solution, is to make index
a global variable (or just out of mainFunction
). But I need index to stay in
mainFunction`.
How can I make index
increment every time (using the same reference) mainFunction
gets called?
I tried assigning mainFunction
to a variable, then calling the variable in the event listener,
var test = mainFunction;
window.addEventListener('click', test)
but that didn't work. The results were the same.