javascript - 函数表达式和声明中局部变量的作用域

javascript - scope of local variables in function expressions and declarations

在 SO 和 Ben Alman 的 good article, I still quite didn't understand the scope of local variables. I also read this good article 中阅读之后。

function foo(){
  var i=0;
  console.log(++i);
}
foo(); //1
foo(); //1

//##################

var foo = function(){
  var i=0;
  console.log(++i);
};

var x = foo;
x(); //1
x(); //1

//##################

function foo2(){
  var i = 0;
  return function(){
     console.log(++i);
  };
}

var x = foo2();
x(); //1
x(); //2 -- I don't get this

为什么在第三个例子中,我似乎可以有一个单例函数,在多次调用后具有相同的公共内部变量,即使它调用i=0

那是因为您多次调用了 内部函数 ,它由 main 函数 main 函数返回function(foo2) 只执行一次。因此没有重置发生,我不断增加。

因此 foo2() 被调用一次,内部函数调用两次。

var x = foo2();

当你这样做时,我被初始化为 0 并返回一个函数。请注意,您不再使用此函数,而将仅使用返回的函数。

   x();

那一行执行返回的函数,哪一行只执行那一行

console.log(++i);

x(); 

还是一样。