为什么会内存泄漏?
发布于 8 年前 作者 MiYogurt 3119 次浏览 来自 问答
function addHandler() {
    var el = document.getElementById('el');
    el.onclick = function() {
        el.style.backgroundColor = 'red';
    }
}

因为对 el 的引用不小心被放在一个匿名内部函数中。这就在 JavaScript 对象(这个内部函数)和本地对象之间(el)创建了一个循环引用。

照他这么说我岂不是在函数里面用外部的变量都泄露了。

async friendList(){
 let users =  await this.fetchUser();
 let domList = document.querySelector('.user-list');
 _.each(users, (item) => {
    var userDom = document.createElement('div').innerText(item.username);
	domList.appendChild(userDom);
 })
}

domList有内存泄漏吗?

6 回复

@151263

a = {};
a.init = function(){
	a.name = 'ChenMingMing';
	this.name2 = 'ChenLaoDa';
	a.loadDoc = function(){console.log('loaded')};
	console.log(a);
	console.log(this);
	console.log(a===this);
	console.log(Object.is(a,this));
}

既然a和this相等,为什么用a会内存泄漏,用this就不会。

@MiYogurt a跟this都不会内存泄露, 不可能会, 如果你看到某文章说会, 那就是那文章说的应该是IE6 当然,如果a是全局变量, 那么, a跟this都不会被垃圾回收释放内存

@151263 哦,我是在MDN上面看到的。 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/A_re-introduction_to_JavaScript#内存泄露

你看看。

@MiYogurt 里面说明了, 是IE才会这样, “在 IE 中,每当在一个 JavaScript 对象和一个本地对象之间形成循环引用时,就会发生内存泄露。” ----准确的说是IE6

@151263 好吧,我以为那个是上一个例子的解释。谢谢您的解释。

回到顶部