为什么闭包中的自由变量值在直接访问时只returns初始值?
Why a free variable value in closure only returns the initial value when it is accessed directly?
function Counter() {
var c = 0;
function increment() {
c++;
}
function getC() {
return c;
}
return { increment, getC, c };
}
var { increment, getC, c } = Counter();
increment();
increment();
increment();
increment();
console.log(getC()); // 4
console.log(c); // 0
我对上面的行为感到困惑,尤其是最后一行。
我预计 c
也 returns 4
以及 getC()
但它只是 returns 初始值 0.
有人可以帮助我了解幕后发生的事情吗?
当您将 c
传递给 return { increment, getC, c }
时,c
传递它的值而不是它的引用,因为它是原始类型(简单例如:数字、字符串)。
因此函数 return 不会被后续的函数调用改变。
请注意,getC
起作用的原因是因为该函数访问原始 c
引用,而不仅仅是值。
function Counter() {
var c = 0;
function increment() {
c++;
}
function getC() {
return c;
}
return { increment, getC, c };
}
var { increment, getC, c } = Counter();
increment();
increment();
increment();
increment();
console.log(getC()); // 4
console.log(c); // 0
我对上面的行为感到困惑,尤其是最后一行。
我预计 c
也 returns 4
以及 getC()
但它只是 returns 初始值 0.
有人可以帮助我了解幕后发生的事情吗?
当您将 c
传递给 return { increment, getC, c }
时,c
传递它的值而不是它的引用,因为它是原始类型(简单例如:数字、字符串)。
因此函数 return 不会被后续的函数调用改变。
请注意,getC
起作用的原因是因为该函数访问原始 c
引用,而不仅仅是值。