爲了方便開發者不去關心內存分配的事情,javascript 在變量申明的時候就已經順便分配了內存。java
var n = 123; // 給一個number分配內存 var s = "azerty"; // 給一個string分配內存 var o = { a: 1, b: null }; // 給一個object分配內存 var a = [1, null, "abra"]; // (和object同樣)給一個array及裏面的值分配內存 function f(a){ return a + 2; } // 給一個function分配內存(function也能夠看成一個object) // 函數的表達式一樣也是至關於給一個object分配內存 someElement.addEventListener('click', function(){ someElement.style.backgroundColor = 'blue'; }, false);
var d = new Date(); var e = document.createElement('div');// 給一個dom元素分配內存
var s = "azerty"; var s2 = s.substr(0, 3); // s2 是一個新的string // 因爲strings是一些不可變的值組成的,javascript可能不會給其分配內存,而只是存儲一個[0,3]的範圍 var a = ["ouais ouais", "nan nan"]; var a2 = ["generation", "nan nan"]; var a3 = a.concat(a2); // 新的array,包含四個元素,分別由a和a2的元素組成
var o = { a: { b:2 } }; // 建立了兩個對象,一個引用了另一個對象做爲其屬性 顯然,都不能夠被回收 var o2 = o; // o2 也引用了 o o = 1; // 如今,o中原始的對象有一個惟一的引用 o2的變量中 var oa = o2.a; // 引用o2的a屬性 // 這個對象產生了兩個引用,一個是o2的a對象,另外一個一個是oa變量 o2 = "yo"; // 原始的o對象如今是0引用 // o能夠被回收 // 然而其屬性a仍然被oa引用了,所以其內存不能被釋放 oa = null; // 原始對象o中的a是0引用了 // 此時能夠被回收
function f(){ var o = {}; var o2 = {}; o.a = o2; // o 引用了 o2 o2.a = o; // o2 引用了 o return "azerty"; } f();
var div = document.createElement("div"); div.onclick = function(){ doSomething(); }; // div 經過 事件引用了其onclick屬性 // handler一樣引用了div // 循環引用,內存泄露