Thursday, 12 October 2017

JavaScript Closure



<!DOCTYPE html>
<html>
<head>
    <title></title>
       <meta charset="utf-8" />
    <script>
        var myCount = (function () {
            var count = 0;
            return ++count;
        })();
    </script>
</head>
<body>
    <input type="button" name="name" value="Count" onclick="alert(myCount)" />
</body>
</html>


Problem with Script :

Count Value will get reset every time

 



    <script>
        var myCount = (function () {
            var count = 0;
            return function () {
                return ++count;
            }
        })();
    </script>


  <input type="button" name="name" value="Count" onclick="alert(myCount)" />


About Script contains closure but it will return

  

Below code invokes inner function on button click

 
 



No comments:

Post a Comment