如何理解JavaScript中的闭包?

How to understand closures in Javascript?

本问题已经有最佳答案,请猛点这里访问。

如何理解JavaScript中的闭包?

In general terms, a closure is a function bound to one or more external variables. When it is called, the function is able to access these variables. In JavaScript, closures are often implemented when functions are declared inside another function. The inner function accesses variables of the parent one, even after the parent function has terminated

在这句话中,"闭包是一个绑定到一个或多个外部变量的函数",是否意味着我们可以这样做:var myFun = Function(msg){...};是正确的?

"即使在父函数终止之后"是什么意思?


closure is a function bound to one or more external variables

这个概念的一个例子是函数条被绑定到外部变量x、y和z:

1
2
3
4
5
6
7
8
9
10
function foo(x, y) {
  var z = 3;

  return function bar(a, b, c) {
    return (a + b + c) * (x + y + z);
  };
}

var closure = foo(1, 2);
closure(5, 6, 7); // (5 + 6 + 7) * (1 + 2 + 3) = 24

变量closure是指调用foo返回的内部函数bar。调用closure就像在foo中重新输入作用域,这样可以查看foo的所有局部变量和参数。

even after the parent function has terminated

这意味着在执行foo之后,存储在closure变量中的返回函数保持foo的状态。您甚至可以通过再次调用foo来创建多个独立的闭包:

1
2
3
4
5
6
7
8
var closure = foo(1, 2);
closure(5, 6, 7); // (5 + 6 + 7) * (1 + 2 + 3) = 24

var closure2 = foo(0, 0);
closure2(5, 6, 7); // (5 + 6 + 7) * (0 + 0 + 3) = 21

/* closure2 does not affect the other closure */
closure(5, 6, 7); // (5 + 6 + 7) * (1 + 2 + 3) = 24


我不确定您是从哪里引用的,但听起来好像它是在引用父函数运行完成的时间。


您对外部变量的解释不正确。这真的意味着它可以做到:

1
2
3
4
5
6
7
8
9
10
11
function make_closure()
{
    var x = 20;
    return function()
    {
        alert(x);
    };
}

var closure = make_closure();
closure(); // Displays 20