常見的內(nèi)存泄露
標簽:
JavaScript
js垃圾回收的方式:1、标记清楚。 2、引用计数
1、 意外的全局变量
function foo(arg) { bar = "this is a hidden global variable"; }// 实际上是function foo(arg) { window.bar = "this is an explicit global variable"; }// 偶然创建全局变量function foo() { this.variable = "potential accidental global"; }
以上变量再非严格模式下都会挂载到window下面, 即使函数执行完毕也不会销毁变量,所以造成内存泄露。
解决办法: 这种写法在严格模型'use strict';
下面会抛出异常, 此外严格模式还可以避免错误。 所以项目中应该使用严格模式
2、被遗漏的定时器和回调函数
// 被遗漏的定时器const someResource = getData(); setInterval(function() { var node = document.getElementById('Node'); if(node) { // Do stuff with node and someResource. node.innerHTML = JSON.stringify(someResource)); } }, 1000);// 被遗漏回调函数var element = document.getElementById('button');function onClick(event) { element.innerHtml = 'text'; } element.addEventListener('click', onClick); element.removeEventListener('click', onClick); element.parentNode.removeChild(element);
3、DOM 之外的引用
var elements = { button: document.getElementById('button'), image: document.getElementById('image'), text: document.getElementById('text') };function doStuff() { image.src = 'http://some.url/image'; button.click(); console.log(text.innerHTML); // Much more logic}function removeButton() { document.body.removeChild(document.getElementById('button')); }
4、闭包
var theThing = null;var replaceThing = function () { var originalThing = theThing; var unused = function () { if (originalThing) console.log("hi"); }; theThing = { longStr: new Array(1000000).join('*'), someMethod: function () { console.log(someMessage); } }; }; setInterval(replaceThing, 1000);
作者:EdmundChen
链接:https://www.jianshu.com/p/f046c59d27e5
點擊查看更多內(nèi)容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦