垃圾收集:对象属性 [英] Garbage collection: object properties

查看:87
本文介绍了垃圾收集:对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个对象包含其他对象作为其属性,如

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

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

obj 超出范围时 - 做所有嵌套对象都是隐式销毁的,或者我需要迭代它们并且删除显式?

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; 

垃圾收集后,假设没有创建其他引用,那么obj和obj的空间['42 ']将被恢复,保存的值当然会被保留。

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:如评论中所述 delete obj 无效,因为 obj 被声明为 var 。如果 obj 是一个全局对象,因此是全局对象的属性, delete 就可以了。要有效删除var,请使用 obj = null
我学会测试的一件事是删除一个运算符并返回 true

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.

这篇关于垃圾收集:对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆