Jquery Closure Example - Jquery

How to use closure concept in jquery?

Snippet Code


  
Rate this page :
  [ 0 votes]

The closure can access the variable count in parent scope. The function closure() will return value of a self invoking function. It sets the count to zero (0),and returns a function expression. The same way that notclosure() function returns the count value but it does not have the scope of the variable. This shows a simple Jquery closure code, where the scope of variable is explained.

<script type='text/javascript'> var closure = (function () { var count = 0; return function () {return count += 1;} })(); function test(){ document.getElementById("demo").innerHTML = closure(); } function notclosure() { var count = 0; return count += 1; } function test1(){ document.getElementById("demo1").innerHTML = notclosure(); } </script> <input type="button" onclick="test()" value='Check Closure'> <p id="demo">0</p> <input type="button" onclick="test1()" value='Check Function'> <p id="demo1">0</p>

Tags


Ask Questions

Ask Question