将本地对象存储在全局对象中

时间:2017-05-31 20:20:57

标签: javascript object scope

该函数生成新对象 - 我们事先不知道 - 我想将它们存储起来以供日后使用。这没关系:

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 个答案:

答案 0 :(得分:0)

根据MDN

  

...此算法减少了&#34的定义;不再需要对象" to"一个对象没有引用它的其他对象"。如果指向此对象的引用为零,则该对象被视为可以收集垃圾。

因此,只要您引用这些对象,他们就不会被垃圾收集。 例如:

  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;  
相关问题