Recently, I came across an example of JavaScript closure that left me puzzled.
The example code is as follows:
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;
If you click on the element `size-12`, for example, it triggers the anonymous function inside `makeSizer` which changes the font size to 12 pixels. Simple enough, right?
But what's confusing to me is when I make a slight alteration to the original code:
function makeSizer(size) {
document.body.style.fontSize = size + 'px';
}
And then call `makeSizer(12)` directly instead of assigning it to `size12` for the click event, it no longer works.
I understand that this showcases the power of closures in JavaScript, but why does my modified version not produce the desired result?
Sincerely, Charles.