我使用 setTimeout() 有两个类似的函数,但它给了我两个不同的结果

问题描述 投票:0回答:1

在函数调用 call1 和 call2 中,我试图实现相同的目标,即延迟 1000 秒打印值。但我注意到,在 call1() 中,变量 timer 在不同的函数调用之间持续存在而在 call2 中,当第二次调用 call2 时,第一次调用中的变量 timer 不存在。为什么会发生这种情况?如果您为我提供一些资源,以便我了解这一点,那将会很有帮助 代码:

const myFunction= (d) => {
    let timer ;
    return function(){
        if (timer) console.log("funCall1 : timer is still present");else console.log("funCall1 : timer not present")
        timer = setTimeout(()=>{
            console.log("funCall1 : inside setTimeout")
        },d)
    }
}

const call1=myFunction(1000)

function call2(){
  let timer;
  if(timer)
  console.log("funCall2 : timer is present")

  timer = setTimeout(()=>{
    console.log("funCall2 : abc")
  },1000)
}

call1()
call1()
call1()

call2()
call2()
call2()

我使用在线编译器编译了上面的代码programiz:JSCompiler

输出

funCall1 : timer not present
funCall1 : timer is still present
funCall1 : timer is still present
funCall1 : inside setTimeout
funCall1 : inside setTimeout
funCall1 : inside setTimeout
funCall2 : abc
funCall2 : abc
funCall2 : abc
javascript asynchronous settimeout local-variables event-loop
1个回答
0
投票

call1
中,我们称之为
closure
Closure
是您要查找的关键字。

© www.soinside.com 2019 - 2024. All rights reserved.