Reputation: 160
I have a simple goal, I would like to increment a variable but I'm facing the closure problem. I've read why this s happening here How do JavaScript closures work?
But I can't find the solution to my problem :/
let's assume this part of code I took from the link.
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); //incrementation
}
num++;
return sayAlert;
}
I would like to increment num within the function and to keep the changes to num.
How could I do that ?
Here is the JsFiddle where I have my problem, I can't figure out how to increment my totalSize and keep it.
I don't want a local variable that ends up with closure.
Upvotes: 1
Views: 95
Reputation: 15413
From your fiddle, I guess the problem is a mix of closure (totalSize
should be outside of the loop) and query.exec
being asynchronous (this one can be verified with some console.log
).
What you seem to need is some kind of control flow, something like async.reduce
Upvotes: 2
Reputation: 227
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num++); //incrementation
}
return sayAlert;
}
var inscrese = say667();
so if you want to increase by one just call increase();
Upvotes: 0
Reputation: 87311
If all other solutions fail, then make num an array: var num = [666]
, then increment it's first element: num[0]++
.
Upvotes: -1