在JavaScript中删除对象 [英] Deleting Objects in JavaScript

查看:94
本文介绍了在JavaScript中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript的 delete 运算符有点困惑。以下面的代码片段:

  var obj = {
helloText:Hello World!
};

var foo = obj;

删除obj;

执行完这段代码后, obj null ,但是 foo 仍然指向一个完全像 obj 。我猜这个对象与 foo 指向的对象是一样的。



这让我感到困惑,因为我期望写删除obj 删除了 obj 在内存中指向的对象 - 不仅仅是变量 obj



这是因为JavaScript的垃圾收集器在保留/释放的基础上工作,所以如果我没有其他的变量指向这个对象,它会从内存中删除?



(顺便说一下,我的测试是在Safari 4中完成的。)

解决方案

delete操作符只会删除一个引用,而不会删除一个对象本身。如果它确实删除了对象本身,那么其他剩余的引用就会像C ++删除那样悬而未决。 (并且访问它们中的一个会导致崩溃,为了使它们全部变为空,意味着在删除每个对象或额外的内存时需要额外的工作。)

由于Javascript是垃圾收集,你不需要自己删除对象 - 当无法再引用它们时,它们将被删除。

如果您完成对象的引用,那么删除对象的引用会非常有用,因为这会为垃圾回收器提供有关可回收内容的更多信息。如果引用保留给一个大对象,这可能会导致它不被回收 - 即使程序的其余部分实际上并未使用该对象。


I'm a bit confused with JavaScript's delete operator. Take the following piece of code:

var obj = {
    helloText: "Hello World!"
};

var foo = obj;

delete obj;

After this piece of code has been executed, obj is null, but foo still refers to an object exactly like obj. I'm guessing this object is the same object that foo pointed to.

This confuses me, because I expected that writing delete obj deleted the object that obj was pointing to in memory—not just the variable obj.

Is this because JavaScript's Garbage Collector is working on a retain/release basis, so that if I didn't have any other variables pointing to the object, it would be removed from memory?

(By the way, my testing was done in Safari 4.)

解决方案

The delete operator deletes only a reference, never an object itself. If it did delete the object itself, other remaining references would be dangling, like a C++ delete. (And accessing one of them would cause a crash. To make them all turn null would mean having extra work when deleting or extra memory for each object.)

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed. If references remain to a large object, this can cause it to be unreclaimed - even if the rest of your program doesn't actually use that object.

这篇关于在JavaScript中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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