javascript closure not working as it should
<p>see the first code:</p>

<pre><code> var count = 0;
 (function addLinks() {
   var count = 0;//this count var is increasing

   for (var i = 0, link; i &lt; 5; i++) {
     link = document.createElement("a");
     link.innerHTML = "Link " + i;

     link.onclick = function () {
       count++;
       alert(count);
     };

     document.body.appendChild(link);
   }
 })();
</code></pre>

<p>When the link gets clicked the counter variable keeps on increasing for each link element. This is the expected result.</p>

<p>Second:</p>

<pre><code>var count = 0;
$("p").each(function () {
  var $thisParagraph = $(this);
  var count = 0;//this count var is increasing too.so what is different between them .They both are declared within the scope in which closure was declared

  $thisParagraph.click(function () {
    count++;
    $thisParagraph.find("span").text('clicks: ' + count);
    $thisParagraph.toggleClass("highlight", count % 3 == 0);
  });
});
</code></pre>

<p>Here the closure function is not working as expected. On each click on the paragraph element, the counter <code>var</code> is increased but that increment is not displayed on click on second paragraph element? What is the reason for this? Why is this happening? The count variable is not increasing for each paragraph element.</p>
