当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Garbage collection: object properties

问题描述:

Let's say I have an object that contains another objects as its properties like

var obj = {

'1': {...},

'42': {...}

};

When obj gets out of scope - do all nested objects destroyed implicitly or I need to iterate over them and delete explicitly?

网友答案:

Yes, unless another reference still exists :

var obj = {
    '1': {...},
    '42': {...}
};


var save = obj['1'];

obj = null; 

After garbage collection and assuming no other references have been created then the space for obj and obj['42'] would be recovered, the value of saved would of course be preserved.

Mea culpa : as mentioned in the comments delete obj in my original is not valid since obj was declared as a var. Had obj been a global and hence a property of the global object, delete would have worked fine. To effectivly delete a var, use obj = null. One thing I learned testing this was that delete an operator and returns true or false.

分享给朋友:
您可能感兴趣的文章:
随机阅读: