I read the How do JavaScript closures work? question and thought i finally understood closures.
Especially this point is very confusing right now:
Example 7
This final example shows that each call creates a separate closure for the local variables. There is not a single closure per function declaration. There is a closure for each call to a function. ..........................................
Ok, so Example 7 shows this example:
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);
document.write('num: ' + num +
'; anArray: ' + anArray.toString() +
'; ref.someVar: ' + ref.someVar + "<br>");
}
}
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;
This example works for me as it should.
So I experiemented a little and i don't really understand why this code doesn't work (looks like it doesn't even create a new closure on function call)
function createCounter(startValue){
var localCounter;
this.setCounter = function(firstValue) {
localCounter = firstValue;
}
this.getValue = function(){return localCounter;};
this.increment = function(){localCounter++;};
this.setCounter(startValue);
return this;
}
var Counter1 = createCounter(1);
document.write(Counter1.getValue()); //1
Counter1.increment();
var Counter1Value = Counter1.getValue(); // 2
var Counter0 = createCounter(0); //works as it should if i put a "new createCounter(0) here, but why?
document.write("<br >Counter 1 oldValue:" + Counter1Value); //2
document.write("<br >Counter 1 currentValue:" + Counter1.getValue()); //0 (why is the localvariable overwritten?)
document.write("<br >Counter 0 currentValue:" + Counter0.getValue()); // //0
why do i need to add the "new" keyword to create a second closure, and why are both Counter1 and Counter0 using the same localCounter variable?