javascript - JS自执行闭包: what happens when IIFEs inside have conflicting declarations?

标签 javascript closures iife

我正在经历JavaScript allonge#six并来到这个示例(每行代码后的简短注释):

((PI) => {             //1 - Outer - PI = 3.14 
   ((PI) => {})(100);   // 2 - IIFE (LOCAL)  PI = 100


  // ((PI) => PI)(100) // alternative1 = LOCAL PI = 100
 //  ((PI) => {return PI;})(100) // alternative2 - LOCAL PI = 100

  return (diameter) => diameter * PI;  // 3 - PI = 3.14
})(3.14)(2)

在所有这些情况下,外部函数中以 PI 为界的参数直接传递到 return 语句,从而忽略 IIFE。隐藏“PI”参数的唯一方法是将 return 语句更改为:

((PI) => (diameter) => diameter * PI)(100)

所以第一个问题:除了这种情况下的闭包之外,还有其他方法可以隐藏 PI 参数(绑定(bind)在外部函数上的参数)吗?

此外,我通过 google 开发者控制台逐行运行代码,并在代码中找到了一个点,其中 IIFE 内的 PI 值被“覆盖”为 3.14,尽管之前限制为 100。PI inside the IIFE gets overwritten to 3.14 DESPITE BEING BOUNDED TO 100 previously

第二个问题:

执行后IIFE内部发生了什么变化,什么时候PI值被覆盖为3.14?

最佳答案

我发现很难弄清楚您到底在问什么。因此,我只是重新组织了代码并添加了自己的注释,试图让自己的事情变得更清晰,并希望能够回答您的部分问题。

var a = (function a(PI) {
   // In this scope, PI = 3.14

   (function b(PI) {
     // PI = 100
   })(100);

  return function c(diameter) {
    // PI = 3.14, still in scope `a`
    // diameter = 2, passed in from second call
    return diameter * PI;
  };
});

a_result = a(3.14); // == c, with PI = 3.14
c_result = a_result(2); // c called with diameter = 2, PI = 3.14 from scope `a`

请随时使用名称和引用资料提出更多有关此问题的问题,以便我达成共识。

关于javascript - JS自执行闭包: what happens when IIFEs inside have conflicting declarations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38817729/

相关文章:

javascript - 这个 JavaScript 模式叫什么,为什么要使用它?

javascript - 避免 CoffeeScript 传递对象引用样式的方法

javascript - react native : filling form without use of state (stateless form)

ios - 优化捕获列表

javascript - javascript中的关闭和回调内存泄漏

javascript - 针对 RegExp 的 Google Closure 编译器警告

javascript - iife 返回的函数无法正常工作

javascript - 了解 IIFE

javascript - getJSON,在调用之前更改 api 调用 url 变量

javascript - 使用 jQuery 将输入 TITLE 显示为 VALUE(包括 jsfiddle)