After reading about closures in JavaScript, I am still unable to understand where are they used? If there were no closures then how would the things be done alternately (if possible) and what does the use of closures simplify. If someone can explain this with some code examples in JavaScript it would be helpful. Any links to articles explaining this are also welcome. I have read this article mentioned in a similar question. It explains with code like this
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
But why would I do like this when instead I can easily create a function like this
function sizer(size) {
document.body.style.fontSize = size + 'px';
};
document.getElementById('size-12').onclick = function(){sizer(12)};
document.getElementById('size-14').onclick = function(){sizer(14)};
document.getElementById('size-16').onclick = function(){sizer(16)};