2016-01-07 17 views
0

如果垃圾收集器具有代碼中的某些引用,則垃圾收集器不會從DOM元素中清除。但是如果這個引用在裏面附加到這個元素監聽器呢?GC清除會刪除其偵聽器中引用的元素變量嗎?

<span id="element">aga</span> 
<script> 
    function attach() { 
     var element = document.getElementById("element"); 
     element.addEventListener("click", function() { 
      //1) if element isn't used in this function 
      console.log('aga'); 
      //2) if element is used in this function 
      console.log(element); 
     }); 
    } 
    attach(); 

    document.body.innerHTML = ''; 
</script>  

回答

0

如果垃圾回收「正確」由瀏覽器來實現(特別是如果它使用Mark-and-sweep algorithm),即DOM元素應該被收集,因爲它現在是全球範圍可達。

您的問題可能與GC實現僅使用引用計數算法時導致潛在內存泄漏的循環引用有關。請參閱上述鏈接瞭解更多詳情。

您可能也對這個帖子感興趣:What is JavaScript garbage collection?