I saw this as an example on MDN and didn’t understand why this was a Good Thing (TM).
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
Why is the above better than the below?
function makeSizer(size) {
document.body.style.fontSize = size + 'px';
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
What does it do differently? Obviously, I’m missing the point…
EDIT: Adding rest of code (full code was in link)
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>
In this case
sizeis variable that is enclosed. CallingmakeSizer(12)returns a function reference that ‘remembers’ 12. This function reference is assigned to a click handler on an element (see the rest of the code in the MDN-example). It says: if you click me, call (execute)size12. On clicking thus the font size of the body becomes ’12px’ because the function reference returned frommakeSizer(12)is executed (with the enclosed value of 12).If you would’ve used the function you would have resized the font immediately.
Think what would happen in this scenario when you did:
Would anything happen if you clicked
#size-12?The MDN-page you linked to links to a jsfiddle example. Try it out!
Good or bad are things I happily leave to the more religious part of the community. I would say this closure is useful, even handy perhaps.