意外的全局变量

1
2
3
4
5
6
7
8
9
10
11
12
13
// a没有定义类型,会默认为全局变量,在fun执行后不会被销毁
function fun() {
a = 10
}
func()
console.log(a)

// 通过this创建a,fun执行后,this指向window,a成为了全局变量
function fun() {
this.a = 10
}
func()
console.log(a)

未清理的DOM元素引用

1
2
var a = document.getElementById('id');
document.body.removeChild(a);

不能回收,因为存在变量a对它的引用。虽然我们用removeChild移除了,但是还在对象里保存着#的引用,即DOM元素还在内存里面。
解决方法: a = null;

定时器

1
2
3
4
5
6
7
8
9
10
11
12
// 定时器执行后,会导致定时器的回调函数及其内部依赖的变量都不能被回收,造成内存泄漏
let temp = 'hello'
setTimeout(()=>{
console.log(temp)
},500)

//解决方案:将定时器赋值,在不需要定时器的时候,手动清除定时器(调用clearInterval或者clearTimeout)
let temp = 'hello'
const timer = setTimeout(()=>{
console.log(temp)
clearTimeout(timer)
},500)

闭包

1
2
3
4
5
6
7
8
9
10
11
12
// 闭包会维持函数作用域的引用,使其得不到释放
let fun = function() {
let hello = 'hello'

return function () {
console.log(hello)
}
}

fun()() //hello

fun = null //通过赋值为空进行释放

console.log

在传递给 console.log的对象是不能被垃圾回收 ♻️,因为在代码运行之后需要在开发工具能查看对象信息。所以最好不要在生产环境中 console.log任何对象。