JavaScript闭包初识

这段时间在复习JavaScript,今天刚好看到介绍闭包closure的这段:

Here is a case that might surprise you:

var variable = "top-level";
function parentFunction() {
  var variable = "local";
  function childFunction() {
    print(variable);
  }
  return childFunction;
}

var child = parentFunction();
child();
运行结果是:local。

这说明,虽然child在parentFunction函数的作用域之外,当parentFunction执行完return childFunction;这条语句之后,child仍然能够访问到处于parentFunction内部的variable变量,而此时parentFunction早已执行完成。

是不是很诡异。是的,这就是JavaScript闭包。

简单说来,closure就是:一个函数的return值是其内部定义的子函数。

如果还是不明白,这里有一个解释,真是一语道破天机:A function defined inside another function retains access to the environment that existed in that function at the point when it was defined.

你可能感兴趣的:(JavaScript,闭包,closure)