How to understand closures in Javascript?
This question already has an answer here:
closure is a function bound to one or more external variables
An example of this concept is that the function bar is bound to the external variables x, y, and z:
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
The variable closure
refers to the inner function bar
returned from the call to foo
. Invoking closure
is like reentering the scope within foo
, which gives visibility into all of foo
's local variables and parameters.
even after the parent function has terminated
This means that after foo
is executed, the returned function stored in the closure
variable persists the state of foo
. You can even create multiple independent closures by invoking foo
again:
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
Your interpretation of external variables is incorrect. It really means it can do this:
function make_closure()
{
var x = 20;
return function()
{
alert(x);
};
}
var closure = make_closure();
closure(); // Displays 20
我不确定你从哪里引用,但是它听起来像是在父功能完成运行时引用的。
链接地址: http://www.djcxy.com/p/1482.html上一篇: Node.js JavaScript语法
下一篇: 如何理解Javascript中的闭包?