0

I have a question which has most likely a simple answer... I'm reading about closures and the like, but don't quite grasp it yet.

ar=[];
r=10;
ar[1]=function (bb) { node.warn ("b:"+bb+"--"+r); }
r=20;
ar[2]=function (cc) { node.warn ("c:"+cc+"--"+r); }

ar[1](2); // output= b:2--20
ar[2](3); // output= c:3--20

I would expect the output if the first to be "b:2--10" and not "b:2--20". So how do I 'fix' this 'r' variable into this function?

I can use two different variables of course (as per suggestion), but this is only an example - I would use this function and call it when needed, each time the same variable will be used, but each time it will have another value.

thanks!

Wannes
  • 41
  • 5
  • You're calling the functions after `r` is set to `20`, so that's what it is. – adeneo Dec 16 '15 at 11:47
  • You'll need two different `r` variables, one for every function. – Bergi Dec 16 '15 at 11:48
  • Hi Bergi, yes, in this code I could use two variables, but this is only a small example of what I ultimately would want to do: use a function and call it when needed, each time using the same variable which will have another value. – Wannes Dec 16 '15 at 12:08
  • but indeed -- this has already been answered in another post - sorry for the duplicate – Wannes Dec 16 '15 at 12:09
  • No, I mean that you cannot use the same variable when you expect different values. You can however dynamically create variables (even multiple ones with the same name) - every function call introduces a new scope with new variables. Check the answers of the duplicate question for code examples, if those don't suffice feel free to [edit] your question and I'll reopen&answer. – Bergi Dec 16 '15 at 12:10

0 Answers0