Skip to content

Instantly share code, notes, and snippets.

@iuliaL
Last active September 16, 2016 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iuliaL/bfa14775b4bc11490114e5456084af05 to your computer and use it in GitHub Desktop.
Save iuliaL/bfa14775b4bc11490114e5456084af05 to your computer and use it in GitHub Desktop.
closure structure
function outerFunction(){
var someCount = 0;
return function innerFunction(){
someCount++;
console.log("Called ",someCount," times");
}
}
var counter = outerFunction();
counter(); // "Called 1 times"
counter(); // "Called 2 times"
//========================================== example
function makeBirdCounter() {
var count = 0;
return function(){
count += 1;
return count + ' birds';
}
}
var birdCounter = makeBirdCounter();
birdCounter(); // "1 birds"
birdCounter(); // "2 birds"
//========================================== for loop closure example
// 3 buttons: First Second Third
//<!DOCTYPE html>
//<html>
//<head>
// <title>Array of Loops</title>
//</head>
//<body>
// <button id="first">First</button>
// <button id="second">Second</button>
// <button id="third">Third</button>
//script type="text/javascript" src="setUpHandlers.js"></script>
//</body>
//</html>
var buttons = document.getElementsByTagName('button');
for(var i = 0; i < buttons.length; i += 1) {
var button = buttons[i];
var buttonName = button.innerHTML;
button.addEventListener('click', function(){
console.log(buttonName);
});
} // this will output Third so won't work -> it needs a closure
function createHandler(name) {
return function(){
console.log(name);
}
}
for(var i = 0; i < buttons.length; i += 1) {
var button = buttons[i];
var buttonName = button.innerHTML;
button.addEventListener('click', createHandler(buttonName));
}
// or use let instead of var
for(var i = 0; i < buttons.length; i += 1) {
var button = buttons[i];
let buttonName = button.innerHTML;
button.addEventListener('click', function(){
console.log(name);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment