Skip to content

Instantly share code, notes, and snippets.

@paulkoegel
Last active August 29, 2015 13:56
Show Gist options
  • Save paulkoegel/9252076 to your computer and use it in GitHub Desktop.
Save paulkoegel/9252076 to your computer and use it in GitHub Desktop.
JavaScript closures illustrated
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src='javascript.js'></script>
<link href="style.css" media="all" rel="stylesheet" type="text/css">
</head>
<body>
<h1>
JavaScript Closures Illustrated
</h1>
<h3>Normal Loop</h3>
<div class='normal-loop'>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>10</button>
</div>
<br><hr><br>
<h3>Closure Loop</h3>
<div class='closure-loop'>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>10</button>
</div>
<footer>
Inspired by Mark Dalgleish's excellent talk <a href='http://markdalgleish.com/presentations/gettingclosure/'>"Getting Closure"</a><br><br>
Paul Wittmann - <a href='https://twitter.com/wakkahari'>@wakkahari</a> - <a href='mailto:paul@railslove.com'>paul@railslove.com</a>
</footer
</body>
</html>
$(function() {
// normal loop
for(var i = 0; i < 10; i++) {
$element = $('.normal-loop button').eq(i);
$element.click(function() {
alert('You clicked on button #' + (i+1));
});
}
// loop using closures - thus emulating block scope (cf. http://markdalgleish.com/presentations/gettingclosure)
for(var j = 0; j < 10; j++) {
(function(j) {
$element = $('.closure-loop button').eq(j);
$element.click(function() {
alert('You clicked on button #' + (j + 1));
});
})(j);
}
});
body {
font-family: 'Helvetica Neue', Helvetica, Arial;
}
.normal-loop, .closure-loop {
padding: 20px;
}
.normal-loop {
background: red;
}
.closure-loop {
background: green;
}
button {
font-size: 18px
}
footer {
margin-top: 50px;
font-size: 16px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment