Hedger Wang 在国内 blog 上得到的方法:使用 try … finally 结构来使对象最终为 null ,以阻止内存泄露。
其中举了个例子:
function createButton() {
var obj = document.createElement("button");
obj.innerHTML = "click me";
obj.onclick = function() {
//handle onclick
}
obj.onmouseover = function() {
//handle onmouseover
}
return obj;//return a object which has memory leak problem in IE6
}
var dButton = document.getElementById("d1").appendChild(createButton());
//skipped....
对于 IE6 中,引起内存泄露的原因,可看《Understanding and Solving Internet Explorer Leak Patterns》一文。
上面的例子,应该属于上文中的 “Closures”原因。
.gif)
再看下用 try … finally 的解决方法:
/**
* Use the try ... finally statement to resolve the memory leak issue
*/
function createButton() {
var obj = document.createElement("button");
obj.innerHTML = "click me";
obj.onclick = function() {
//handle onclick
}
obj.onmouseover = function() {
//handle onmouseover
}
//this helps to fix the memory leak issue
try {
return obj;
} finally {
obj = null;
}
}
var dButton = document.getElementById("d1").appendChild(createButton());
//skipped....
可能大家有疑问: finally 是如何解析的呢?
答案是:先执行 try 语句再执行 finally 语句。
例如:
function foo() {
var x = 0;
try {
return print("call return " + (++x));
} finally {
print("call finally " + (++x));
}
}
print('before');
print(foo());
print('after');
返回的结果为:
print » before
print » call return 1
print » call finally 2
print » true
print » after
更多详细的演示:《Finally, the alternative fix for IE6’s memory leak is available》
相关的一些讨论:《Is “finally” the answer to all IE6 memory leak issues?》
witter:
共有8 条评论
我觉得:
这样的写法,没有多少实际用际.
比如:
var MyWin = function(){
this.create = function(){…}
this.show = function(){…}
}
var win1 = new MyWin();
…
Show!
如果你把 win1 给 等于 null 的�¯?,这个程�º?无任何作用.
所以,您说的这�§?方法,用处很�°?.
@xling 不知道为什么你的评论有乱码,转译了一下,还有部分转不过–!
真是的,人家就用别的语言评论,你却想把它转译。。。
这样的解决方法我测试了一下,不能解决内存溢出的问题,释放DOM对象并不意味着这个DOM的Javascript引用也被释放了。
http://javascript.crockford.com/memory/leak.html
这个方法才正解,虽然感觉上效率差了点,不知道有否更简单的解决办法。
实在不行就升级到IE7,或者换个其它的!
还是有一部分人用IE6的.
moz的wiki上有一段关于内存泄露的原因
http://developer.mozilla.org/cn/docs/A_re-introduction_to_JavaScript#.E5.86.85.E5.AD.98.E6.B3.84.E9.9C.B2
楼主的这个不完整 哪个里面说的是一个闭包和一个dom对象互相引用
@netwjx 是IE6特有的内存泄漏问题,具体的可以看文中给出的链接