JavaScript中“将闭包赋值给变量”表述是否正确?及代码解释优化
Great question! To cut to the chase: Yes, this statement is accurate and unambiguous—though we can refine the wording to be even clearer if needed.
Here's why: In JavaScript, a closure is defined as the combination of a function and the lexical environment (scope) in which it was declared. When you return an inner function (like bar in your example) from an outer function (foo), that inner function retains access to the outer function's scope even after the outer function has finished executing. So when you assign this returned inner function to a variable (like func1 or func2), you're effectively storing the entire closure in that variable—because the function carries its associated lexical scope with it.
Deep Dive into Your Example Code
First, let's fill in the expected console outputs and break down what's happening:
function foo() { let a = 1; return function bar() { a += 100; console.log(a); } } let func1 = foo(); let func2 = foo(); func1(); // 101 func2(); // 101 func1(); // 201 func2(); // 201
Key Explanations:
- Every call to
foo()creates a brand new lexical scope with its ownavariable (initialized to 1). It then returns thebarfunction, which "closes over" this scope. func1holds the closure from the firstfoo()call: itsbarfunction has exclusive access to the firstavariable.func2holds a completely separate closure from the secondfoo()call: itsbarfunction accesses a distinct, unrelatedavariable.- Each call to
func1()modifies its owna(1 → 101 → 201), while calls tofunc2()modify its owna(1 → 101 → 201).
Rewritten, Precise Comments
Here's a cleaned-up version of your original comments, fixing the error in the original (it incorrectly referenced calling bar() instead of foo()) and making the wording more concise:
/* 第9行:声明变量`func1`,赋值为调用`foo()`返回的闭包函数(持有自身的`a`变量访问权)。 第10行:声明变量`func2`,赋值为另一次`foo()`调用返回的独立闭包函数。 `func1`与`func2`各自的闭包指向两个完全独立的同名变量`a`,互不干扰。 程序控制台输出: - 101 - 101 - 201 - 201 */
内容的提问来源于stack exchange,提问作者Dima Naida

