I thought I was starting to understand JavaScript quite well but clearly not. Let me explain my problem with an example. First I have the following module defined:
var Test = function() {
var counter = 0;
function init() {
alert(counter);
}
return {
counter: counter,
init: init
}
};
I then create 2 instances:
var test1 = new Test();
var test2 = new Test();
Now I update the counter variable (as it is public) and do some alerts. So far so good.
alert(test1.counter); // Alerts 0
test1.counter = 5;
alert(test2.counter); // Alerts 0
test2.counter = 10;
alert(test1.counter); // Alerts 5
Now finally I say the following:
test1.init(); // Alerts 0
test2.init(); // Alerts 0
This is the bit I don't understand. Why does this alert 0? I thought the first alert would be 5 and the second 10.
I'd appreciate if someone could explain how the above could works or point me in the right direction. Thanks
return { counter: counter, ... }
just copies currentvar counter
value and changingthis.counter
does not affectvar counter
. – Excise