首页 > 开发 > JS > 正文

JS 的循环引用, 原因是什么?

2017-09-05 13:02:01  来源:网友分享

Mozilla 文档上的例子, 这个是在 IE 6,7 里的,
https://developer.mozilla.org/en-US/docs/JavaScript/Memory_Management

var div = document.createElement("div");div.onclick = function(){  doSomething();}; // The div has a reference to the event handler via its 'onclick' property// The handler also has a reference to the div since the 'div' variable can be accessed within the function scope// This cycle will cause both objects not to be garbage-collected and thus a memory leak.

这里说的, 函数里有一个对 div 的引用, 可是在哪, 是 this 么?
在 Chrome Firefox 里是否有类似的内存泄漏问题?
这是语言设计的失误么?

解决方案

这和《Javascript高级程序设计》中函数表达式的一段很像

function assignHandler () {  var element = document.getElementById('someElement');  element.onclick = function () {    alert(element.id);  };}

书上描述“由于匿名函数中引用了element,所以element的引用数最少是1,导致占用的内存永远不会被回收。”,把这个就叫内存泄漏。

建议写法

function assignHandler () {  var element = document.getElementById('someElement');  var id = element.id;  element.onclick = function () {    alert(id);  };  element = null;}

个人觉得内存非常规的占用就应该算作内存泄漏,而不是非得无限增加的内存占用。