问题描述
我对 JavaScript 的 delete
运算符有点困惑.取下面一段代码:
var obj = {helloText:世界你好!"};var foo = obj;删除对象;
这段代码执行完后,obj
是null
,但是foo
仍然引用一个和obj完全一样的对象代码>.我猜这个对象与
foo
指向的对象相同.
这让我很困惑,因为我期望编写 delete obj
删除了 obj
在内存中指向的对象——而不仅仅是变量 obj
>.
这是因为 JavaScript 的垃圾收集器在保留/释放的基础上工作,所以如果我没有任何其他变量指向该对象,它会从内存中删除吗?>
(顺便说一下,我的测试是在 Safari 4 中完成的.)
delete 操作符只删除一个引用,而不是一个对象本身.如果它确实删除了对象本身,则其他剩余的引用将悬空,就像 C++ 删除一样.(并且访问其中一个会导致崩溃.让它们全部变为 null 意味着在删除或每个对象的额外内存时需要额外的工作.)
由于 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 中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!