【发布时间】:2010-03-14 16:36:13
【问题描述】:
下面的例子,只是一个例子,我知道当用户点击div块时我不需要一个对象来显示一个警告框,但这只是一个简单的例子来解释一个在编写JS时经常发生的情况代码。
在下面的示例中,我使用了一个全局可见的对象数组来保存对每个新创建的 HelloObject 的引用,这样在单击 div 块时调用的事件可以使用数组中的引用调用 HelloObject 的公共函数 hello()。
首先看一下代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Test </title>
<script type="text/javascript">
/*****************************************************
Just a cross browser append event function, don't need to understand this one to answer my question
*****************************************************/
function AppendEvent(html_element, event_name, event_function) {if(html_element) {if(html_element.attachEvent) html_element.attachEvent("on" + event_name, event_function); else if(html_element.addEventListener) html_element.addEventListener(event_name, event_function, false); }}
/******************************************************
Just a test object
******************************************************/
var helloobjs = [];
var HelloObject = function HelloObject(div_container)
{
//Adding this object in helloobjs array
var id = helloobjs.length; helloobjs[id] = this;
//Appending click event to show the hello window
AppendEvent(div_container, 'click', function()
{
helloobjs[id].hello(); //THIS WORKS!
});
/***************************************************/
this.hello = function() { alert('hello'); }
}
</script>
</head><body>
<div id="one">click me</div>
<div id="two">click me</div>
<script type="text/javascript">
var t = new HelloObject(document.getElementById('one'));
var t = new HelloObject(document.getElementById('two'));
</script>
</body></html>
为了获得相同的结果,我可以简单地替换代码
//Appending click event to show the hello window
AppendEvent(div_container, 'click', function()
{
helloobjs[id].hello(); //THIS WORKS!
});
使用此代码:
//Appending click event to show the hello window
var me = this;
AppendEvent(div_container, 'click', function()
{
me.hello(); //THIS WORKS TOO AND THE GLOBAL helloobjs ARRAY BECOMES SUPEFLOUS!
});
因此会使 helloobjs 数组变得多余。
我的问题是:您认为第二个选项是否会在 IE 上造成内存泄漏或可能导致浏览器运行缓慢或崩溃的奇怪循环引用?
我不知道如何解释,但来自 C/C++ 编码员的背景,以第二种方式执行听起来像是某种循环引用,可能会在某些时候破坏内存。
我还在网上看到了关于 IE 关闭内存泄漏问题http://jibbering.com/faq/faq_notes/closures.html(我不知道它是否在 IE7 中得到修复,如果是,我希望它不会在 IE8 中再次出现)。
谢谢
【问题讨论】:
标签: javascript memory-leaks closures