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
在这句话中,"闭包是一个绑定到一个或多个外部变量的函数",是否意味着我们可以这样做:
"即使在父函数终止之后"是什么意思?
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 |
变量
even after the parent function has terminated
这意味着在执行
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 |