It stays 0
is because you are not changing the variable inside Test
, you are changing the object returned by the function. counter
is kept "private" and only a function in Test
can access it.
var Test = function() {
var counter= 0;
function init() {
alert(counter);
}
function changeNum(n){
counter = n; //add a function inside `Test` so that it can
} //access the variable
return {
counter: counter,
init: init,
changeNum: changeNum
}
};
Now it will work: http://jsfiddle.net/DerekL/pP284/
var test1 = new Test();
alert(test1.counter); //0
test1.init(); //0
test1.changeNum(5);
alert(test1.counter); //5
test1.init(); //5
For more information, see JavaScript Closures.