How to use closures function in JavaScript

1 Answer

0 votes
<!DOCTYPE html>
<html>
<body>

<button type="button" onclick="countFunction()">Click To Count</button>

<p id="msg">0</p>

<script>

var count = (function () {
    var c = 0;
    return function () {return c += 1;} // Private variable
})();

function countFunction()
{
    document.getElementById("msg").innerHTML = count();
}

/*
run:

1..2..3..4..5... (as long as you click...+1 .. +1 .. +1)

*/

</script>
</body>
</html>

 



answered Jul 1, 2015 by avibootz
edited Jul 25, 2015 by avibootz

Related questions

...