javascript working of closure
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/14645471/javascript-closure-not-working-as-it-should">javascript closure not working as it should</a>  </p>
</blockquote>



<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);//here all the paragraph updates the same variable
        };

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

<p>when the link gets clicked the counter variable keeps on increasing for each link element .This is an aspected reult</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 aspected.On each click on the paragraph element ,the counter var is increased but that increment is not displayed on click on second paragraph element?What is the reason behing this?Why is this happening?the count variable is not increasing for each paragraph element.At my previous question i didn't got the satisfied answer so i requestioned</p>
