js垃圾回收的方式:1、标记清楚。 2、引用计数
1、 意外的全局变量
function foo(arg) {
bar = "this is a hidden global variable";
}// 实际上是function foo(arg) { window.bar = "this is an explicit global variable";
}// 偶然创建全局变量function foo() { this.variable = "potential accidental global";
}以上变量再非严格模式下都会挂载到window下面, 即使函数执行完毕也不会销毁变量,所以造成内存泄露。
解决办法: 这种写法在严格模型'use strict';下面会抛出异常, 此外严格模式还可以避免错误。 所以项目中应该使用严格模式
2、被遗漏的定时器和回调函数
// 被遗漏的定时器const someResource = getData();
setInterval(function() { var node = document.getElementById('Node'); if(node) { // Do stuff with node and someResource.
node.innerHTML = JSON.stringify(someResource));
}
}, 1000);// 被遗漏回调函数var element = document.getElementById('button');function onClick(event) {
element.innerHtml = 'text';
}
element.addEventListener('click', onClick);
element.removeEventListener('click', onClick);
element.parentNode.removeChild(element);3、DOM 之外的引用
var elements = { button: document.getElementById('button'), image: document.getElementById('image'), text: document.getElementById('text')
};function doStuff() {
image.src = 'http://some.url/image';
button.click(); console.log(text.innerHTML); // Much more logic}function removeButton() { document.body.removeChild(document.getElementById('button'));
}4、闭包
var theThing = null;var replaceThing = function () { var originalThing = theThing; var unused = function () { if (originalThing) console.log("hi");
};
theThing = { longStr: new Array(1000000).join('*'), someMethod: function () { console.log(someMessage);
}
};
};
setInterval(replaceThing, 1000);
作者:EdmundChen
链接:https://www.jianshu.com/p/f046c59d27e5