看到的第一個代碼:JavaScript的關閉不工作,因爲它應該
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);
}
})();
當鏈接被點擊的計數器變量不斷爲每個鏈接元素增加。這是預期的結果。
二:
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);
});
});
這裏如期關閉功能無法正常工作。每次單擊段落元素時,計數器var
都會增加,但在第二段元素上單擊時不會顯示該增量值?這是什麼原因?這是爲什麼發生?每個段落元素的count變量不會增加。
傳遞給'。點擊()函數'本身是一個封閉,和你做的第一件事情之一是設置局部變量'count'爲'0 '在裏面; 「count」的值永遠不會變成別的,因爲你明確地告訴它總是0. –