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
You can always create multiple instances of a class! This is what classes are designed for! Each object will hold its own individual inner variables (unless they are static, in which case they are shared). If you wish to pass a list of categories to a function, or return a list of categories.
Users of this Terraform module can create multiple similar resources by using for_each meta-argument within module block which became available in Terraform 0.13.
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.
This is what happened:
counter
variable, which is defined inside Test scope, holding a reference to it.counter
, set to value of internal counter
.counter
, by setting test1.counter = X, but the init() still holds a reference to original variable.That's why you see the old value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With