javascript - JavaScript 闭包的一个包罗万象的定义

标签 javascript closures scope scopes lexical

我已经阅读了 10 篇关于闭包的 SO 引用、MDN 引用和其他博客文章。他们似乎都以自己的方式定义闭包。例如,来自 MDN 文档:

function makeFunc() {
  var name = "Mozilla";
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

这是他们对闭包的解释:

Normally, the local variables within a function only exist for the duration of that function's execution. Once makeFunc() has finished executing, it is reasonable to expect that the name variable will no longer be accessible. Since the code still works as expected, this is obviously not the case.

The solution to this puzzle is that myFunc has become a closure. A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a closure that incorporates both the displayName function and the "Mozilla" string that existed when the closure was created.

下面的 StackOverflow 帖子将闭包作为可见范围的堆栈来回答。 What types of scope exist in Javascript?

我感到困惑的地方:闭包是一个对象吗?或者它只是一种“异常范围情况”,其中内部嵌套函数可以访问在其自身外部定义但对容器父函数而言是本地的变量,即使在父函数已经执行之后也是如此?闭包是引用此嵌套函数(范围)情况的对象,如 myFunc 还是内部函数本身?

最佳答案

简而言之,

The function inside another function, has the access to the variables declared in the outer function. In case the function is in the global context, it obviously has the access to the global variables.

更多上下文:

var v1; // I'm accessible anywhere    
function a() {
    var v2;
    function b() { // I can access v2 and v1
        var v3;
        function c() {  // I can access v1, v2, v3
            var v4;
        }
        return c;
    }
    return b();
}
var f = a();

在上面,a, b, c 都是闭包,它们可以访问它们各自的父作用域并且递归地进行直到 window 或全局上下文。


一般来说,每个函数都是一个闭包。但我们只有在实现某些东西时才会想到它们,实际上 取决于闭包,例如工厂函数。

关于javascript - JavaScript 闭包的一个包罗万象的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28220219/

相关文章:

javascript - Javascript 函数外的正确作用域

php - 在这段 JavaScript 代码中包含变量的正确语法是什么?

ruby-on-rails - 使用 block 命名和创建实例变量 [Ruby-on-Rails]

javascript - 在外部作用域中使用 let 或 const 声明变量之前,在闭包中使用变量是否合法?

javascript - 如何在高阶 javascript 函数中执行变量捕获?

ruby - 当变量超出范围时是否意味着它不存在?

python - 如何在Python中的不同模块之间拥有全局变量

function - 在 Julia 的函数作用域内的 if 语句内定义函数的结果错误

JavaScript 动画位置问题

javascript - 读取 JSON Ajax 响应?