I tried it, but delete
doesn't work.
var x = {"y":42,"z":{"a":1,"b":[1,2,3]}};
alert(x.y);
delete x;
alert(x.y); // still shows '42'
How to delete the full object crossbrowser?
Edit:
x = null
also doesn't work
You can only use the delete operator to delete variables declared implicitly, but not those declared with var. You can set x = null or x = undefined
You don't need to delete objects in JavaScript. The object will be garbage collected after all references to it are removed. To remove the reference, use:
x = null;
You cannot delete a variable or a function. Only a property of an object. You can simply assign:
x = null;
if you want to clear its value.
UPDATE: clarification regarding functions:
>> function f1() {console.log("aa");}
>> f1();
aa
>> delete f1;
false
>> f1();
aa
But if you declare a global function as a window attribute, you can delete it:
>> f1 = f1() {console.log("aa");}
>> delete window.f1;
true
The same is for variables:
>> a = "x";
>> console.log(a);
x
>> delete window.a;
true
>> console.log(a);
ReferenceError: a is not defined
But:
>> var a = "x";
>> console.log(a);
x
>> delete a;
false
>> console.log(a);
x
func1 = function(){}
, then delete window.func1
. It will delete successfull - Matt 2012-04-03 22:02
You can't delete an object from the global namespace in Javascript.
You can delete
objects within x
, but not x
itself.
window.func1 = function(){}
, and then delete window.func1
. I can also do func2 = function(){}
followed by a delete. However, I can not do function func3(){}
. Calling delete on that returns false, and the function remains - Matt 2012-04-03 21:16
Try x = null;
or x = undefined;
.