参考答案

内存泄露的解释:程序中己动态分配的堆内存由于某种原因未释放或无法释放。

  • 根据JS的垃圾回收机制,当内存中引用的次数为0的时候内存才会被回收
  • 全局执行上下文中的对象被标记为不再使用才会被释放

内存泄露的几种场景

  • 全局变量过多。通常是变量未被定义或者胡乱引用了全局变量
// main.js // 场景1 function a(){ b=10; } a(); b++; // 场景2 setTimeout(()=>{ console.log(b) },1000)
  • 闭包。 未手动解决必包遗留的内存引用。定义了闭包就要消除闭包带来的副作用
function closuer (){ const b = 0; return (c)=> b + c } const render = closuer(); render(); render = null; // 手动设置为null,GC会自己去清除
  • 事件监听未被移除
function addEvent (){ const node = document.getElementById('warp'); node.addEventListener('touchmove',()=>{ console.log('In Move'); }) } const onTouchEnd = (){ const node = document.getElementById('warp'); node. } useEffect(()=>()=>{ const node = document.getElementById('warp'); node.removeEventListener('touchmove'); }) // 类似react 生命周期函数: componentWillUnmount render(<div id='warp' onTouchEnd={onTouchEnd}> // code... </div>)
  • 缓存。建议所有缓存都设置好过期时间。