I've read through the following code for Example 7 posted on the following answer for How do JavaScript Closures work?
function newClosure(someNum, someRef) {
// Local variables that end up within closure
var num = someNum;
var anArray = [1,2,3];
var ref = someRef;
return function(x) {
num += x;
anArray.push(num);
alert('num: ' + num +
'\nanArray ' + anArray.toString() +
'\nref.someVar ' + ref.someVar);
}
}
obj = {someVar: 4};
fn1 = newClosure(4, obj);
fn2 = newClosure(5, obj);
fn1(1); // num: 5; anArray: 1,2,3,5; ref.someVar: 4;
fn2(1); // num: 6; anArray: 1,2,3,6; ref.someVar: 4;
obj.someVar++;
fn1(2); // num: 7; anArray: 1,2,3,5,7; ref.someVar: 5;
fn2(2); // num: 8; anArray: 1,2,3,6,8; ref.someVar: 5;
I used the same logic for my example
function increment() {
var id = 0;
return function(number) {
id += number;
alert('Unique ID: ' + id);
}
}
six = increment();
fourteen = increment();
six(6);
fourteen(8);
In the example I took inspiration from,
fn1(2); //num 7
The num outputs 7 because according to my understanding, it has been set to 5 from the previous call first time around. So using the same reasoning, I expected the fourteen(8) call to return the number 14 because I believed ID would have been updated to 6 rather than stay at 0. Why is the variable not static? How would I account for it to be static?
I also tried to have the function set a parameter of number and set the ID equal to the parameter but that did not update it either.
http://jsfiddle.net/de9syawe/4/ to show.