【发布时间】:2021-11-07 04:34:56
【问题描述】:
假设我们已经跟随 sn-ps:
function Counter() {
let count = 0
function inc() {
count += 1
}
function dec() {
count -= 1
}
function getCount() {
return count
}
return { getCount, inc, dec, count }
}
const counter = Counter()
counter.inc()
counter.inc()
console.log(counter.getCount()) // 2
console.log(counter.count) // 0
我想知道为什么使用函数getCount() 并直接返回count 变量会显示不同的结果。在我看来,它们都引用了相同的count 地址,在inc() 调用之后,它的值应该相应地改变。
【问题讨论】:
-
没有。一个引用变量,另一个引用属性(在使用值
0创建它后从未更新)。 -
return { count }不返回“变量”,而是返回当时的值。
标签: javascript closures