题解 | #计数器#
计数器
https://www.nowcoder.com/practice/59154c37d06c41b5b0e19b3b26272229
考察闭包,closure没用被销毁,
因为它return的函数被赋给了timer,
只要timer不被销毁,
closure就一直不被销毁,
里面的num也会一直存在
const closure = () => {
// 补全代码
let num = 0
return function () {
return ++num
}
}
还可以用this
const closure = () => {
// 补全代码
return function () {
if (!this.num) {
this.num = 1
} else {
this.num++
}
return this.num
}
}
}
