Closures
by Nitrium
HTML
<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>
<h1>this is a h1</h1>
<h2>this is a h2</h2>
CSS
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
JavaScript
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;
// ------------------------------
function sayHello2(name) {
var text = 'Hello ' + name; // local variable
var sayAlert = function() {
alert(text);
}
return sayAlert;
}
var testSay = sayHello2('giliar');
document.getElementById('size-16').onclick = testSay;
// ----------------------------------
var adder = function (x) {
return function (y) {
return x + y;
};
};
add5 = adder(5);
add5(1) == 6;