function createIncrement() {
let count = 0;
function increment() {
count++;
}
let message = Count is ${count}
;
function log() {
console.log(message);
}
return [increment, log]; } const [increment, log] = createIncrement(); increment(); increment(); increment(); log(); // What is logged?
问题
为啥 log()输出 Count is 0? increment 闭包 ha 函数为啥不缓存 count 的值?
为啥把 let message = Count is ${count}
移到 log 函数内就能输出 Count is 3?
function log() {
let message = Count is ${count}
;
console.log(message);
}
1
dvsilch 2022-11-12 21:21:23 +08:00
message 定义在闭包外
|
2
sweetcola 2022-11-12 21:22:22 +08:00
message 没有变啊,message 是字符串,不会随 count 改变而改变。
|
3
wiluxy 2022-11-13 23:28:53 +08:00
你把 count 返回,打印一下,count 是有变的,问题在于 message 的值在定义的时候就确定了是 ’Count is 0‘,把 message 改为函数调用就符合你的预期了
```js function createIncrement() { let count = 0; function increment() { count++; } let message = () => `Count is ${count}`; function log() { console.log(message()); } return [increment, log]; } const [increment, log] = createIncrement(); increment(); increment(); increment(); log(); // Count is 3 ``` |