2017-05-31 69 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;