I am confusing with the use of closure and self-revoking in Javascript. When I run this code, each time I click the Button the counter increases by 1. It seems that the function assigned to "add" is self-invoking function.
<!DOCTYPE html>
<html>
<body>
<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>
However, when I call the function like the code below, the counter value is always 1.
<!DOCTYPE html>
<html>
<body>
<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(){
var temp = add();
document.getElementById("demo").innerHTML = temp();
}
</script>
</body>
</html>
Could anyone tell me the difference between the two examples, and what goes under the hood? Thanks for you help.
0
– Manh Quang Jul 18 '17 at 13:16