JavaScript: Closure Examples

Example Usage of Functions with & without closure

by Fiddel

HTML

<a href="#" id="size-20">20</a>
    <a href="#" id="size-30">30</a>
    <a href="#" id="size-40">20 + 20</a>

CSS

body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}

JavaScript

//Example Functions with/without Closure


function WithClosure(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}


function WithoutClosure(size) {
  return  document.body.style.fontSize = size + 'px';
}

function WithClosureAdvanced(x) {
  return function(y) {    
    return  document.body.style.fontSize = x + y + 'px';
  };
}



//Runs Straight Away
var size20 = WithoutClosure(20);

//Runs When Called
var size30 = WithClosure(30);

//Runs When Called
var size40 = WithClosureAdvanced(20);
console.log(size20);
console.log(size30);
document.getElementById('size-20').onclick = size20;
document.getElementById('size-30').onclick = size30;
document.getElementById('size-40').onclick = size40(20);//This will runs straight away setting the size to 40px;
document.getElementById('size-40').onclick = function() { size40(20);
};