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);
};
document.body.appendChild(link);
}
})();
When the link gets clicked the counter variable keeps on increasing for each link element. This is the expected result.
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 expected. 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 for this? Why is this happening? The count variable is not increasing for each paragraph element.
do you mean: