具有多个嵌套 IIFE 的函数作用域

Function Scope with multiple nested IIFE's

我在这个 JavaScript 练习中遇到了问题。我得到了一个函数,它定义了三个不同的 variable/value 对,并且在该函数内有多个嵌套的 IIFE,它们会更改这些相同的值。练习的目标是将变量的值更改为特定值。所以这里是我看到的代码:

var scopeExercise = function() {
  var a = 1,
    b = 2,
    c = 3;
  result = "a: " + a + ", b: " + b + ", c: " + c;

  (function firstFunction() {
    var b = 5,
      c = 6;

    (function secondFunction() {
      var b = 8;

      (function thirdFunction() {
        var a = 7,
          c = 9;

        (function fourthFunction() {
          var a = 1,
            c = 8;
        })();
      })();
    })();
  })();

  return result;
};

console.log(scopeExercise());

他们想要 var a = 1、b = 8 和 c = 6。我仍然无法理解函数范围,因为我已经尝试注释掉 thirdFunction 和 fourthFunction,这样他们就不会在外部函数之前被调用,它仍然不会改变 var a、b 和 c 的值。另外,我不明白为什么嵌套函数没有执行,因为它们应该立即被调用。

试试这个:

var scopeExercise = function () {
  var a = 1, b = 2, c = 3;
  (function firstFunction() {
    b = 5; 
    c = 6;
    console.log('firstFunction()');
    (function secondFunction() {
      b = 8;
      console.log('secondFunction()');
      (function thirdFunction() {
        a = 7;
        c = 8;
        console.log('thirdFunction()');

        (function fourthFunction() {
          a = 1, 
          c = 6;
          console.log('fourthFunction()');
        })();
      })();
    })();
  })();
  result = "a: " + a + ", b: " + b + ", c: " + c;
  return result;
}
console.log(scopeExercise());

添加了您将看到所有功能都已执行的打印件