gre*_*reg 3 javascript garbage-collection
我正在努力确保当我完成它们时,包含在闭包中的一些变量将被释放用于垃圾收集.我不确定天气将它们设置为未定义,或者删除它们就足够了.有什么想法吗?
// 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")
})
Run Code Online (Sandbox Code Playgroud)
看一下这篇文章,了解垃圾收集的更多细节.
由于您要向.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)
Run Code Online (Sandbox Code Playgroud)
该函数(function(p,t){ ... })(photo, tmp)将被收集,因为它是匿名的,不再被引用.但它返回的函数将被添加到tmp.onload哪个将持续存在.
如果你想确保收集的东西设置变量,当你完成它们时,要未定义或为null.这样,垃圾收集器将确保范围内没有引用,从而释放它们.