2017-05-31 74 views
-1

該函數生成新對象 - 我們之前不知道 - 我想將它們存儲以備後用。這是好的:在全局對象中存儲本地對象

var objs = {};// container 

(function doSth(){// might has to add new objects 
    var ob1 = {id: 29938, name: 'name1'}; 
    objs['ob1'] = ob1;// ??? 
    objs['ob2'] = {id: 2000, name: 'name2'};// ??? 
})() 

// use the obj later on like 
console.log(objs['ob1'].id); 
console.log(objs['ob2'].name); 

我在堆上創建一個新的對象,並將引用存儲在全局對象內供以後使用。因爲我存儲引用沒有垃圾收集完成,訪問是好的,我假設。
JsFiddle for this.

+1

當然。任何可以訪問的對象都不是垃圾,所以不會被收集。 – Barmar

+1

本地和全局對象都不存在。只有局部和全局變量。 – Barmar

+0

是的,沒關係。它會很好地工作。 –

回答

0

根據MDN

...此算法減少了「不需要對象了。」「一個對象沒有其他對象引用它」的定義。如果零引用指向此對象,則該對象被視爲垃圾收集。

所以只要你有這些對象的引用,他們將不會被垃圾收集。 例如:

var o = { 
    a: { 
     b: 2 
    } 
    }; // 2 objects are created. One is referenced by the other as one of its properties. 
    // The other is referenced by virtue of being assigned to the 'o' variable. 
    // Obviously, none can be garbage-collected 
    // You can also free the memory by removing all references to that object, e.g., 
    o.a = null;