由$$end产生的关于 GC 的疑惑

内存泄漏的问题

function assignHandler() {
    var el = document.getElementById('demo');
    el.onclick = function() {
        console.log(el.id);
    }
}
assignHandler();

以上代码创建了作为el元素事件处理程序的闭包,而这个闭包又创建了一个循环引用,只要匿名函数存在,el的引用数至少为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对象的引用,确保正常回收其占用内存。

疑惑

  1. 在内存中维持一个变量。这个特殊变量有名字吗?
  2. 什么时候由于闭包造成的特殊变量,会被垃圾回收。
  3. 如何看到闭包导致的特殊变量存储在内存中,chrome调试能看到吗?尝试一下。
  4. 闭包的垃圾回收机制高级版本浏览器肯定也是技术引用。但它是怎么处理的具体。

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.

参考文献

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容