JavaScript:确保闭包中的对象被垃圾回收

4

我正在尝试确保一些包含在闭包中的变量在使用完后能够被垃圾回收。我不确定将它们设置为未定义或删除它们是否足够。你有什么想法吗?

// run once for each photo, could be hundreds
$("img.photo").each( function(){
    // create the vars to put in the callback
    var photo = $(this);
    var tmp = new Image();

    // set the callback, wrapping the vars in its scope
    tmp.onload = (function(p,t){
      return function(){ 
        // do some stuff

        // mark the vars for garbage collection
        t.onload = ?
        t = ?
        p = ?
    })(photo, tmp)

    // set the source, which calls onload when loaded
    tmp.src = photo.attr("src")
})
3个回答

7

请查看这篇文章,了解垃圾回收的更多细节。

由于您正在向.each发送匿名函数,因此该函数及其内部的所有内容将被垃圾回收。 除了其中的一部分:

// set the callback, wrapping the vars in its scope
tmp.onload = (function(p,t){
  return function(){ 
    // do some stuff

    // mark the vars for garbage collection
    t.onload = ?
    t = ?
    p = ?
})(photo, tmp)

这个函数 (function(p,t){ ... })(photo, tmp) 会被收集起来,因为它是匿名的并且不再被引用。但它返回的函数会被添加到 tmp.onload 中并持久存在。

如果你想确保被收集,当你使用完变量后,将其设置为 undefined 或 null。这样垃圾回收器就能确定在作用域中没有引用,从而释放它们。


2
当你的“onload”函数退出时,没有任何东西会引用该闭包本身,因此整个闭包将被收集。

-3

JavaScript负责处理那些使用var关键字声明的变量,其作用域已经离开执行环境。

对于声明的对象,请使用delete关键字释放内存。

x = new Object;
alert(x.value);
delete (x);
alert(x); //this wouldn't show

您也可以在JavaScript垃圾回收是什么?找到一些有用的内容。


2
delete 不会释放内存。它只是删除一个引用(这很好,否则 var x = {a: 0}; var y = x; delete x; alert(y.a) 将会造成严重后果)。而且你不能删除变量 - user395760

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接