【发布时间】:2022-01-10 17:48:38
【问题描述】:
为什么在示例 1 和示例 2 中返回不同的结果? 一个 conter 变量(示例 1)实例仍然可以从全局范围访问。
示例 1:
const increment = (()=> {
let counter = 0;
//console.log(counter);
const credits = (num) => console.log(`I have ${num} credit(s).`);
return () => { counter++; credits(counter); }
})();
increment();//I have 1 credit(s).
increment();//I have 2 credit(s).
示例 2:
function a() {
let counter = 0;
const credits = (num) => console.log(`I have ${num} credit(s).`);
return () => { counter++; credits(counter); }
}
a()();//I have 1 credit(s).
a()();//I have 1 credit(s).
谢谢。
【问题讨论】:
-
你的 IIFE 只被调用一次,但
a被调用了两次,每个调用都有自己的counter初始化为 0。 -
试试这个版本,只调用一次
a:const b = a(); b(); b();
标签: javascript scope iife