当前位置:   article > 正文

【前端学习——js篇】1.闭包问题

【前端学习——js篇】1.闭包问题

具体可见https://github.com/febobo/web-interview

闭包问题

function fn(){
    let count = 0
    return function fun(){
        count++;
        console.log(`函数被调用${count}`);
    }
}
const result =  fn()
console.log(result()); //1
console.log(result()); //2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

闭包应用:实现数据的私有。如count不能被全局访问,只能在fun()中修改。

内存泄露

  1. result是一个全局变量,代码执行完并不会马上销毁。
  2. result使用fn方法
  3. fn函数用到fun函数
  4. fun函数用到count变量
  5. count被引用就不会被回收,一直存在

手动回收result = null

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号