如果我调用 add() 三次,为什么不每次都将 counter 设置为零,然后返回将 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
,而是每次都创建一个新计数器。