Possible Duplicate:
javascript closure not working as it should
see the first code:
var count = 0;
(function addLinks() {
var count = 0; //this count var is increasing
for (var i = 0, link; i < 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);
}
})();
when the link gets clicked the counter variable keeps on increasing for each link element .This is an aspected reult
Second:
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);
});
});
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
The
countervariable is declared inside the.eachloop. Thus, each<p>has its own counter because the function is executed for each<p>. Any two paragraphs are not updating the same variable.In the first snippet, on the other hand, there is only one
countervariable used (outside the loop), which is being updated by any click on any<p>. As a side note, note that declaring in inside the loop wouldn’t make a difference – you have to create a closure for each<p>separately to have each<p>have its own counter variable.