如何在javascript中销毁对象?

时间:2022-05-03 17:05:03

I'm wondering how to properly destroy an object in Javascript that contains an array among other data.

我想知道如何正确销毁包含其他数据中的数组的Javascript中的对象。

For example (this is the initial state of the object):

例如(这是对象的初始状态):

acme.models.nomination = {
    recipients : [], // array will be added to later.
    awardType: {}, // this object will be filled out later.
    privacy: 'private',
    ...
};

As the application is used the nomination.recipients object will be added to, along with the other data elements. Is it enough to do the following to clear the complete object when finished with it:

在使用应用程序时,nomination.recipients对象将与其他数据元素一起添加。完成后,是否足以执行以下操作来清除整个对象:

acme.models.nomination = {};

or is this better (or overkill):

或者这是更好(或矫枉过正):

acme.models.nomination.privacy = undefined;
acme.models.nomination.awardType = {};
acme.models.nomination.recipients = {};
acme.models.nomination = {};

I'm thinking that the former statement (i.e. acme.models.nomination = {}) is enough as this effectively makes the entire contents unreachable and hence eligible for garbage collection. However, I'd like to get other peoples opinions on this. BTW, the answer can be given in a modern browser context, let's say browsers post-Jan-2012, as I know memory management was a bit inconsistent in the past.

我认为前一个语句(即acme.models.nomination = {})就足够了,因为这有效地使整个内容无法访问,因此有资格进行垃圾回收。但是,我想就此提出其他人的意见。顺便说一句,答案可以在现代浏览器环境中给出,比如2012年1月之后的浏览器,因为我知道内存管理在过去有点不一致。

1 个解决方案

#1


2  

I think the delete-Operator is what you are looking for:

我认为删除操作符是您正在寻找的:

delete acme.models.nomination;

#1


2  

I think the delete-Operator is what you are looking for:

我认为删除操作符是您正在寻找的:

delete acme.models.nomination;