为什么不在闭包中重置变量 (Javascript)

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() 三次,为什么每次都不将计数器设置为零,然后 return 将计数器递增 1 的匿名函数?自调用函数运行后是否会跳过它?抱歉,如果问题看起来很简单,我很难理解。任何帮助将不胜感激。

If I call add() three times, why dosen't it set counter to zero every time, then return the anonymous funtion that increments counter by one?

因为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 会按照你说的去做,它会 return 一个有自己计数器的新函数,每次你调用它时:

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;};
})();