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.)
var obj = { helloText: "Hello World!" }; var foo = obj; delete obj;
object is not deleted checkobj
delete usage:delete obj.helloText
and then checkfoo now foo is an empty object
– Umair Ahmeddelete
is not for deleting objects in javascript.delete
is used for removing an object key. In your casevar obj = { helloText: "Hello World!" }; var foo = obj; delete obj;
, the object is not deleted. checkobj
. Next, rundelete obj.helloText
and you can see thatfoo
now points to an empty object. """ – Pacerier