I've been getting into OOP javascript recently and more and more I've been hearing about closures. After a day of twisting my brain I now understand them* but I still don't see the advantage over using an object. They appear to to do the same thing but I suspect I'm missing something.
*i think
Edit
I've just spent 20 minutes trying to write an example using a counter written as an object and a counter written as a closure. I have come to the conclusion that I still don't understand closures.
2nd Edit
Ok I've managed to whip of an extremely simple example. There isn't much between these two but I find the object version more readable. Why would I chose one over the other?
/*** Closure way ***/
function closureCounter() {
var count = 0;
return {
increase : function() {
count++;
alert(count);
},
decrease : function () {
count--;
alert(count);
}
};
}
var myCounter = closureCounter();
myCounter.increase();
myCounter.decrease();
/*** Object way ***/
function objCounter() {
var count = 0;
this.increase = function() {
count++;
alert(count);
}
this.decrease = function() {
count--;
alert(count);
}
}
var myCounter = new objCounter();
myCounter.increase();
myCounter.decrease();