ChatGPT解决这个技术问题 Extra ChatGPT

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.)

Full article on the delete keyword webcache.googleusercontent.com/…
@Steve Harrison delete is not for delete an object in javascript delete use for remove an object key in your case var obj = { helloText: "Hello World!" }; var foo = obj; delete obj; object is not deleted check obj delete usage: delete obj.helloText and then check foo now foo is an empty object
@UmairAhmed, Free translation: """ delete is not for deleting objects in javascript. delete is used for removing an object key. In your case var obj = { helloText: "Hello World!" }; var foo = obj; delete obj;, the object is not deleted. check obj. Next, run delete obj.helloText and you can see that foo now points to an empty object. """

J
Jesse Rusak

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.


The delete keyword only works for properties of an object, not variables. perfectionkills.com/understanding-delete
@AlexJM Yes, the next answer from Guffa (and its comments) discusses this in some detail.
A property of an object can be another object. For example; var obj = {a: {}}; delete obj.a;
But... aren't variables actually properties of window?
@Soaku not local variables. (eg those declared with var)
G
Guffa

The delete command has no effect on regular variables, only properties. After the delete command the property doesn't have the value null, it doesn't exist at all.

If the property is an object reference, the delete command deletes the property but not the object. The garbage collector will take care of the object if it has no other references to it.

Example:

var x = new Object();
x.y = 42;

alert(x.y); // shows '42'

delete x; // no effect
alert(x.y); // still shows '42'

delete x.y; // deletes the property
alert(x.y); // shows 'undefined'

(Tested in Firefox.)


If this is executed in the global scope, your x variable becomes just a property on the global window object, and delete x; really does remove the x variable altogether.
@crescentfresh: It's only a property if it's implicitly declared. If it's explicitly declared as in the example, it's a global variable and can not be deleted.
@Tarynn: I see, that's where the problem is. If you do this in the console, for some reason x will not be a proper variable in some browsers, but a property in the window object. This is of course a problem with the console, and doesn't reflect how code is normally executed.
@Guffa After a bunch of research I have to concede it was probably a good thing I didn't have enough rep to down vote. My sincerest apologies, and thanks for taking the time to show me what was happeneing... Here is an indepth explination: perfectionkills.com/understanding-delete/#firebug_confusion
@chao: I see. You are having the same problem as Tarynn (see earlier comments). When you do this in the console it doesn't work the same as in real code.
A
Alex

"variables declared implicitly" are properties of the global object, so delete works on them like it works on any property. Variables declared with var are indestructible.


I never realized var was so badass.
This is a great point, and a JS gotcha. People get used to deleting window vars and then wonder why they can't do the same with local variables.
Same goes for let.
D
David Ackerman

Coming from the Mozilla Documentation, "You can use the delete operator to delete variables declared implicitly but not those declared with the var statement. "

Here is the link: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Operators:Special_Operators:delete_Operator


D
Derlin

delete is not used for deleting an object in java Script.

delete used for removing an object key in your case

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

object is not deleted check obj still take same values delete usage:

delete obj.helloText

and then check obj, foo, both are empty object.


P
Pedro Justo

Setting a variable to null makes sure to break any references to objects in all browsers including circular references being made between the DOM elements and Javascript scopes. By using delete command we are marking objects to be cleared on the next run of the Garbage collection, but if there are multiple variables referencing the same object, deleting a single variable WILL NOT free the object, it will just remove the linkage between that variable and the object. And on the next run of the Garbage collection, only the variable will be cleaned.


g
garek

Just found a jsperf you may consider interesting in light of this matter. (it could be handy to keep it around to complete the picture)

It compares delete, setting null and setting undefined.

But keep in mind that it tests the case when you delete/set property many times.


f
fgb

Aside from the GC questions, for performance one should consider the optimizations that the browser may be doing in the background ->

http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

It appears it may be better to null the reference than to delete it as that may change the behind-the-scenes 'class' Chrome uses.


j
johndhutcheson

IE 5 through 8 has a bug where using delete on properties of a host object (Window, Global, DOM etc) throws TypeError "object does not support this action".

var el=document.getElementById("anElementId");
el.foo = {bar:"baz"};
try{
    delete el.foo;
}catch(){
    //alert("Curses, drats and double double damn!");
    el.foo=undefined; // a work around
}

Later if you need to check where the property has a meaning full value use el.foo !== undefined because "foo" in el will always return true in IE.

If you really need the property to really disappear...

function hostProxy(host){
    if(host===null || host===undefined) return host;
    if(!"_hostProxy" in host){
       host._hostproxy={_host:host,prototype:host};
    }
    return host._hostproxy;
}
var el=hostProxy(document.getElementById("anElementId"));
el.foo = {bar:"baz"};

delete el.foo; // removing property if a non-host object

if your need to use the host object with host api...

el.parent.removeChild(el._host);

C
Craig London

I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop() all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.


H
Hank

This work for me, although its not a good practice. It simply delete all the the associated element with which the object belong.

 for (element in homeService) {
          delete homeService[element];
  }

what is best practice? I remember reading that the delete operator was not best practive for deleting object properties. I believe I read this in Crockford's JavaScript book, but can't dig it up at the moment.