题解 | #计数器#

计数器

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
    }
}
            }


全部评论

相关推荐

点赞 评论 收藏
转发
特斯联 后端开发 300 + 450餐补
点赞 评论 收藏
转发
3 收藏 评论
分享
牛客网
牛客企业服务