Skip to content

Instantly share code, notes, and snippets.

@narensgh
Created July 15, 2019 14:26
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 narensgh/2c8f8e31eff3f91419c677d0d1572fcf to your computer and use it in GitHub Desktop.
Save narensgh/2c8f8e31eff3f91419c677d0d1572fcf to your computer and use it in GitHub Desktop.
Closure implementation with counter example
<!DOCTYPE html>
<html>
<body>
<p>Click the buttons to check the counter implementation.</p>
<button onclick="buttonCounter1()">Button 1</button>
<button onclick="buttonCounter2()">Button 2</button>
<p id="button-counter1"></p>
<p id="button-counter2"></p>
<script>
var counter1 = counter();
var counter2 = counter();
let count1, count2, str;
function pushToDom(element, value, id) {
str = 'Number of times button ' + id + ' is clicked is ' + value;
document.getElementById(element).innerHTML = str;
}
function buttonCounter1() {
count1 = counter1();
pushToDom('button-counter1', count1, 1);
}
function buttonCounter2() {
count2 = counter2();
pushToDom('button-counter2', count2, 2);
}
function counter() {
var count = 1;
return function () {
return count++;
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment