关于闭包的一些知识

120 阅读1分钟

今天上班遇到了一个闭包的问题,直接看例子:

let a = 3
function addTwo(x) {
let ret = x + 2
return ret
}
let b = addTwo(a)
console.log(b)
这个问题是个很简单的闭包问题,答案很容易得到为5

再看一题
function createCounter() {
let counter = 0
const myFunction = function() {
counter = counter + 1
return counter
}
return myFunction
}
const increment = createCounter()
const c1 = increment()
const c2 = increment()
const c3 = increment()
console.log('example increment', c1, c2, c3)

就这一题而言,我刚开始得到结论为c1,c2,c3的值都是1,但是事实上结果分别为1,2,3,这是为什么呢?因为当c1运行结束之后,闭包里面的counter被重新赋值不再是0而是1了,每次运行结束,counter的值会被重新储存于闭包里面,所以可以得到以下结论,c1过后闭包里面的counter值为1,c2过后闭包里的counter值为2,c3过后闭包里面的counter值为3