Created
July 15, 2019 14:26
-
-
Save narensgh/2c8f8e31eff3f91419c677d0d1572fcf to your computer and use it in GitHub Desktop.
Closure implementation with counter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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