【发布时间】:2021-02-02 08:47:03
【问题描述】:
我很好奇示例代码中第 20 行的解释。
在第 9 行声明了名为
func1的变量。 已分配给 函数foo()调用返回的闭包。`
我知道函数foo() 的调用会返回函数bar 和指向其词法范围内的变量a 的指针。既然闭包是a function combined with all of the variables in its lexical scope, including function and class names,我可以说我是把变量func1赋给闭包了吗?
这个解释是否使用了正确的词而不是含糊不清?你能提出一个更好更简洁的解释和解释第 20 行吗?
function foo() {
let a = 1;
return function bar() {
a += 100;
console.log(a);
}
}
let func1 = foo();
let func2 = foo();
func1(); // ???
func2(); // ???
func1(); // ???
func2(); // ???
/*
On line 9 variable with name `func1` is declared.
!! It's assigned to the closure that is returned by the function `foo()` invocation.
The closure contains a pointer to the variable `a` that is in the lexical scope of the function `bar` that is returned by the `foo` invocation.
On line 10 variable with name `func2` is declared. It's assigned to the value of closure that is returned by the function `bar()` invocation. The closure contains a pointer to the variable `a` that is in the lexical scope of the function `bar`.
Variables accessible through the closure during the `func1` invocation and `func2` invocation are two separate independent variables that just happen to have the same name (`a`).
That is, this program would print the following to the console:
- 101
- 101
- 201
- 201
*/
【问题讨论】:
-
func1 在哪里?我个人说变量是“封闭的”,正如 Crockford 先生所说的那样。
-
我会避免说“分配了一个闭包”。这有点误导,太技术化了。 1. 赋值通常是设置变量的值,例如
x = 1是将1赋值给x。你倒着说(意译)x被分配给1。 2.“闭包”其实没什么特别的。 JS 中的每个函数都是一个闭包。我只想说foo()是一个高阶函数,结果是一个函数。
标签: javascript node.js closures