[英]Why Don't Variables Reset in a Closure (Javascript)
我一直在努力學習關閉,但有一件事仍困擾着我。 如果我有以下代碼:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// Returns "3"
如果我調用add()三次,為什么不每次都將counter設置為零,然后返回一個遞增計數器的匿名函數? 一旦自動調用函數運行,它是否會跳過它? 對不起,如果問題看起來很簡單,我很難理解它。 任何幫助將不勝感激。
如果我調用add()三次,為什么不每次都將counter設置為零,然后返回一個遞增計數器的匿名函數?
因為add
是匿名函數,因為包含counter
的函數被調用並且其結果被賦值為add
:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
//^^----------- calls the outer function, returns the anonymous inner function
如果你沒有打電話:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
});
//^--- no () here
...然后add
會按照你說的做,它會返回一個帶有自己的計數器的新函數,每次你調用它:
var add = (function () { var counter = 0; return function () {return counter += 1;} }); var a = add(); var b = add(); var c = add(); console.log("a's first call: " + a()); console.log("a's second call: " + a()); console.log("a's third call: " + a()); console.log("b's first call: " + b()); console.log("b's second call: " + b()); console.log("b's third call: " + b()); console.log("a's fourth call: " + a()); console.log("b's fourth call: " + b());
.as-console-wrapper { max-height: 100% !important; }
這不是重置 counter
,每次創建一個新的計數器。
通過調用add()
您實際上並不執行外部函數,而是執行內部函數。 對於內部函數,counter就像一個全局變量,它已被設置為0
,然后它再也沒有被設置為0
。 在調用add()
您正在執行內部函數內的行,從而增加計數器。
分配給add
的值是IIFE的結果,其中創建了閉包。 也許更明顯當調用add()
時會發生什么,當它的創建編寫如下(相當於原始代碼):
var add;
(function () {
var counter = 0;
add = function () {return counter += 1;};
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.