87,994
社区成员




function makeCounter(){
let count=0;
return function(){
return count++;
};
}
alert(makeCounter()()); // 0
alert(makeCounter()()); // 0
alert(makeCounter()()); // 0
赋值给变量y:
let y=makeCounter();
alert(y()); //0
alert(y()); //1
alert(y()); //2
这个认真的讲是闭包原理,每调用一次makeCounter()都产生一个闭包环境。
在每个闭包环境中都创建一个独立的 count 变量
alert(makeCounter()()); // 0
alert(makeCounter()()); // 0
alert(makeCounter()()); // 0
这样是调用3次makeCounter()。就创建了3个 count 变量
makeCounter()之后的()是调用返回的function(){return count++;}函数,
函数中操作的count是函数所在闭包环境中 count 变量。
每个函数中操作的count都是不同闭包环境中 count 变量。
也就类似于下面这样
if (true) {
let count=0;
alert(count++);
}
if (true) {
let count=0;
alert(count++);
}
if (true) {
let count=0;
alert(count++);
}
赋值给变量y:
let y=makeCounter();
alert(y()); //0
alert(y()); //1
alert(y()); //2
是只调用1次makeCounter()。只创建1个 count 变量
把返回的function(){return count++;}函数赋值给y,
3次调用y函数中操作的count变量都是同一个。
也就类似于下面这样
if (true) {
let count=0;
alert(count++);
alert(count++);
alert(count++);
}