A JavaScript closure confusion

Each time f1() is called that creates a new closure with its own local n variable.

However, the nAdd variable is global, and so gets overwritten every time f1() is called – which means calling nAdd() will only ever add to the n variable in the last closure.

UPDATE: If you want to be able to increment the values of n in each closure independently you could do something like this:

function f1(){
    var n=999;
    return {
        incrementN : function(){n+=1;},
        getN : function f2(){console.log(n);}
    }
}    
var result = f1();
var result2 = f1();
result.getN(); // 999
result.incrementN();
result2.getN();//999
result2.incrementN();
result2.getN();//1000
result.getN();//1000

That is, have f1() return an object containing two methods that are not declared as globals, and that both operate on the local n variable from the closure they belong to.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)