【问题标题】:Understanding the IIFE Scoping in Javascript了解 Javascript 中的 IIFE 范围
【发布时间】:2021-07-02 13:29:28
【问题描述】:

我遇到了类似的事情。有人可以帮我理解为什么会发生这种行为。这与 IIFE 的范围界定有关吗?

const iife = (() => {
    
    let myValue = "Previous";
    const getValue = () => myValue;
    const setValue = (val) => {myValue = val}

return {
    myValue:myValue,
    getValue:getValue,
    setValue:setValue
}

})()

//console outputs
iife //{myValue:"Previous", getValue:f, setValue:f}
iife.setValue("New");
iife.getValue() //"New"
iife // {myValue:"Previous", getValue:f,setValue:f}

即使myValue 变量没有更改,如何获得iife.getValue() = "New" 值?

【问题讨论】:

标签: javascript iife


【解决方案1】:

setValue 更改 iife 函数内的值。当您返回新对象时,它会创建myValue 变量的副本,即iife.myValue !== myValue。修改代码如下即可看到:

const iife = (() => {
    
    let myValue = "Previous";
    const getValue = () => myValue;
    const setValue = (val) => {myValue = val}

    setInterval(() => console.log(myValue), 100)

return {
    myValue:myValue,
    getValue:getValue,
    setValue:setValue
}

})()

//console outputs
iife //{myValue:"Previous", getValue:f, setValue:f}
iife.setValue("New");
iife.getValue() //"New"
iife // {myValue:"Previous", getValue:f,setValue:f}

它将打印您在iife.setValue 中输入的任何内容。

【讨论】:

  • 好的,知道了!所以基本上, iife.myValue 没有被改变,因为没有办法将 myValue 数据写回它。它只是第一次调用时保留的副本。但是在内部 myValue 已经被 setValue 函数改变了。
  • 对,就是这样,两者都是不同的变量
猜你喜欢
  • 1970-01-01
  • 2019-08-20
  • 2022-01-17
  • 2017-11-26
  • 2013-05-23
  • 2012-08-09
  • 2012-08-09
  • 2016-04-23
  • 1970-01-01
相关资源
最近更新 更多