I was reading Closures and it has the example of the following closure.
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val)
{
privateCounter += val;
}
return
{
increment: function()
{
changeBy(1);
},
decrement: function()
{
changeBy(-1);
},
value: function()
{
return privateCounter;
}
}
};
var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value()); /* Alerts 0 */
counter1.increment();
counter1.increment();
alert(counter1.value()); /* Alerts 2 */
counter1.decrement();
alert(counter1.value()); /* Alerts 1 */
alert(counter2.value()); /* Alerts 0 */
I was wondering what the difference and advantages/disadvantages are between this closure and the following code that produce the same results.
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val)
{
privateCounter += val;
};
this.increment= function()
{
changeBy(1);
};
this.decrement= function()
{
changeBy(-1);
};
this.value= function()
{
return privateCounter;
};
};
var counter1 = new makeCounter();
var counter2 = new makeCounter();
alert(counter1.value()); /* Alerts 0 */
counter1.increment();
counter1.increment();
alert(counter1.value()); /* Alerts 2 */
counter1.decrement();
alert(counter1.value()); /* Alerts 1 */
alert(counter2.value()); /* Alerts 0 */
{}button in the toolbar to indent it by 4 spaces. That's how you mark code as code here. Read the rest of the editing help while you're at it. It'd do it for you, but I'm not going to clean all those <br>s out.