Reputation: 11
I'm a JavaScript newbie. Recently I'm learning about JavaScript closures and I'm stuck at the following section:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Closures</h2>
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>
<p id="demo">0</p>
<script>
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
</html>
I understand that the add() function is a self-invoking function and a closure at the same time so it will invoke itself once the webpage is load. The counter will initialize and return 1 immediately. And whenever i press the button (calling the add() function). It should be initialize again and return 1 again. But it turns out my logic is wrong, the counter keeps increasing by 1 when i press the button. I don't understand why as i thought var counter = 0; will be recognized every time and also isn't the variable inside the function should have local scope so after it has executed the counter variable will be destroyed?
Upvotes: 1
Views: 23