Javascript closure example

Written by stevey on October 7th, 2014

<html>
<body>
<div id=”d1″>
<h3>Closure example</h3>

<a href=”javascript:runCounter();”>Run Counter</a>
</div>

</body>
</html>

<script type=”text/javascript”>
function runCounter()
{
var add=(function(){
var counter=0;
return function(){return counter+=1;} //need return for nested function
//var result=(function(){return counter+=1;})(); //this does not work
//alert(result);
})();

alert(add());
alert(add());
alert(add());

}
</script>

 

Leave a Comment