For example I have this function with a closure:
function getData() {
var status = 0;
var func = function() {
status++
alert(status);
}
return func;
}
Its works correctly and the variable "status" is visible within the closure function.
But if I transfer the closure code into the separate function the closure variable "status" isn't available:
function getData() {
var status = 0;
var func = function() {
myFunction();
}
return func;
}
function myFunction() {
status++
alert(status);
}
Yes, I can send this variable to the function and then return the changed value. But what if I need recursion in "myFunction"?
function getData() {
var status = 0;
var a = function() {
myFunction(status);
}
return a;
}
function myFunction(status) {
if (status == 0) {
status = 1;
// After calling this function again "status" will reset to 0,
// but I want to save current value (status = 1).
data();
}
return status++;
}
var data = getData();
data();
How can I get one instance of my variable "status" for all calls to the closure function.
Thanks!