1 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
您誤解了代碼。該函數(shù)add()不包含代碼var counter = 0。
這是完全相同的代碼的重寫(xiě),使其更加清晰:
var add;
// Note: THIS function is NOT add()
(function () {
var counter = 0;
// THIS function is add()
add = function () {counter += 1; return counter}
})();
add(); // 1
add(); // 2
除了如何分配之外,上面的代碼與原始代碼執(zhí)行的操作完全相同add。在您的代碼中,它是通過(guò)返回值分配的,但在上面我只是將它直接分配為全局變量,以便更清楚哪個(gè)函數(shù)是add()。
另一種更像原始代碼的方式是顯式命名這兩個(gè)函數(shù):
var function1 = function () {
var counter = 0;
// The returned function is what will be assigned to add()
return function () {counter += 1; return counter}
}; // Do not call it yet since calling it was what was confusing you
var add = function1();
add(); // 1
add(); // 2
添加回答
舉報(bào)