1

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.

http://jsfiddle.net/knLbv/2/

I don't want a local variable that ends up with closure.

Community
  • 1
  • 1
hyptos
  • 160
  • 1
  • 3
  • 10
  • 4
    So what's the problem? What do you need to achieve? `say667()()` will always alert `667`, as name of function assumes. If you want that returned function alerted incremented value each time, you should move num++ inside body of `sayAlert`. – Tommi Jun 27 '13 at 09:02
  • If you want to access the _global_ variable, then don't use a _local_ variable of the same name in your function. – CBroe Jun 27 '13 at 09:02
  • 1
    Agree with @Tommi. You should post an example of the usage of this function and the expected result so we can understand what you want to achieve – jbl Jun 27 '13 at 09:12
  • I edited the main post, this involve nodejs and mongoose and some xml I catch on steam but it's javascript and it's closure I'm struggling with :/ Should I create a new post ? – hyptos Jun 27 '13 at 10:02

3 Answers3

2

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

jbl
  • 15,179
  • 3
  • 34
  • 101
  • Hey, thanks for the answer what I'm trying to do is getting an xml which contains a lots of information like games the user played. For each game I'm trying to verify if the game exist in my mongoDB, in order to get his size and to add it to a global variable. I don't know if I need another library like socket.io / backbone because I don't really know what they are for. I will look into your control flow. – hyptos Jun 27 '13 at 12:02
  • I didn't use async.reduc but the problem came from the asynchronous trait of query.exec :) – hyptos Jun 30 '13 at 08:33
0
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();

Instance Noodle
  • 227
  • 1
  • 10
-1

If all other solutions fail, then make num an array: var num = [666], then increment it's first element: num[0]++.

pts
  • 80,836
  • 20
  • 110
  • 183