內存泄漏的問題
function assignHandler() {
var el = document.getElementById('demo');
el.onclick = function() {
console.log(el.id);
}
}
assignHandler();
以上代碼創(chuàng)建了作為el元素事件處理程序的閉包,而這個閉包又創(chuàng)建了一個循環(huán)引用,只要匿名函數(shù)存在,el的引用數(shù)至少為1,因些它所占用的內存就永完不會被回收。
function assignHandler() {
var el = document.getElementById('demo');
var id = el.id;
el.onclick = function() {
console.log(id);
}
el = null;
}
assignHandler();//接觸dom對象的引用???到底能有多大的影響,在調試工具上看一下。
把變量el設置null能夠解除DOM對象的引用,確保正常回收其占用內存。
疑惑
- 在內存中維持一個變量。這個特殊變量有名字嗎?
- 什么時候由于閉包造成的特殊變量,會被垃圾回收。
- 如何看到閉包導致的特殊變量存儲在內存中,chrome調試能看到嗎?嘗試一下。
- 閉包的垃圾回收機制高級版本瀏覽器肯定也是技術引用。但它是怎么處理的具體。
by方方
JS 的 GC 不由你控制
用局部變量 會自動 GC
全局變量不 GC
MDN
var div;
window.onload = function(){
div = document.getElementById("myDivElement");
div.circularReference = div;
div.lotsOfData = new Array(10000).join("*");
};
Cycles are not a problem anymore.In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object. Consequently, they will be found unreachable by the garbage collector.
The same thing goes with the second example. Once the div and its handler are made unreachable from the roots, they can both be garbage-collected despite referencing each other.