【问题标题】:IIFE vs noraml functions, Behave differently regarding managing variables in the global scopeIIFE 与普通函数,在全局范围内管理变量时表现不同
【发布时间】: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。
  • 试试这个版本,只调用一次aconst b = a(); b(); b();

标签: javascript scope iife


【解决方案1】:

let counter 行初始化了一个counter 变量。每当该行运行时都会发生这种情况。

在第一个示例中,当您以})() 结尾调用IIFE 时,您运行该行一次,IIFE 返回的函数引用您初始化的counter 变量。

在第二个示例中,每次运行 a 函数时都运行该行 - 每次运行 a() 时都会创建一个新的 counter 变量。所以如果你做a()(),你创建一个计数器变量,在返回的函数中增加它,记录它,然后丢弃它(因为counter不能再被任何东西引用) .调用a()(),然后调用a()() 会产生两个独立的counter 变量,您将这两个变量都加1 并记录。

如果您想通过调整第二个示例来记录 2,请在调用之前将返回的函数分配给一个变量,然后调用该返回的函数两次(而不是调用两次 a)。

function a() {
    let counter = 0;
    const credits = (num) => console.log(`I have ${num} credit(s).`);
    return () => { counter++; credits(counter); }
}
const fn = a();
fn();//I have 1 credit(s).
fn();//I have 2 credit(s).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2013-07-13
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多