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)
M
@151263 哦,我是在MDN上面看到的。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/A_re-introduction_to_JavaScript#内存泄露
你看看。
1
引用 MiYogurt@151263 哦,我是在MDN上面看到的。 https://developer.mozilla.org/zh CN/docs/Web/JavaScript/A re introduction...
@MiYogurt 里面说明了, 是IE才会这样, "在 IE 中,每当在一个 JavaScript 对象和一个本地对象之间形成循环引用时,就会发生内存泄露。" ----准确的说是IE6
M
@151263 好吧,我以为那个是上一个例子的解释。谢谢您的解释。
1
没有
M
@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就不会。
1
引用 MiYogurt@151263 既然a和this相等,为什么用a会内存泄漏,用this就不会。
@MiYogurt a跟this都不会内存泄露, 不可能会, 如果你看到某文章说会, 那就是那文章说的应该是IE6 当然,如果a是全局变量, 那么, a跟this都不会被垃圾回收释放内存
参与回复
登录后即可参与回复。登录