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

Mis*_*ybe 2 javascript closures scope self-invoking-function

我一直在努力学习关闭,但有一件事仍困扰着我.如果我有以下代码:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();

// Returns "3"
Run Code Online (Sandbox Code Playgroud)

如果我调用add()三次,为什么不每次都将counter设置为零,然后返回一个递增计数器的匿名函数?一旦自动调用函数运行,它是否会跳过它?对不起,如果问题看起来很简单,我很难理解它.任何帮助将不胜感激.

T.J*_*der 5

如果我调用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
Run Code Online (Sandbox Code Playgroud)

如果你没有打电话:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
});
//^--- no () here
Run Code Online (Sandbox Code Playgroud)

...然后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());
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
  max-height: 100% !important;
}
Run Code Online (Sandbox Code Playgroud)

那不是重置 counter,每次创建一个新的计数器.