Reputation: 325
Here is code of a page:
<html>
<body>
<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 () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
</html>
There is an enclosure in the script. As i understand, each time when add is called, the counter must be set to zero again, so it doesn't grow when clicking on the button. But as practice shows, my conclusion is wrong. Please tell me, why the counter is not reset each time when the fumction add is called?
Upvotes: 2
Views: 2326
Reputation: 687
Based on your updated code, the correct behavior is for counter
to NOT reset to zero and increase by one.
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
The reason is because the function you return and assign to add is only this part:
function () {return counter += 1;}
Every time you call add()
only that is called. The reason is because you have an anonymous function that declares counter
and returns a function. That function gets placed into add
and traps the counter
variable in a closure.
Upvotes: 1
Reputation: 1084
You need to make it into a seperate function for true closure, then you can call the function.
<body>
<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;
var x = function () {return counter += 1;}
return x();
};
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
Upvotes: 0