简体   繁体   中英

How to delete an object in Javascript crossbrowser

var obj = {
    destroy: function(){this = null;}
};

obj.destroy();

This works in Chrome, however firefox is throwing an error referencing this for some reason. Is there a better way to kill this object within a method?

Error:

invalid assignment left-hand side
[Break On This Error] destroy: function(){this = null;} 

Not sure why Chrome allows for it but you can't assign a value to this. You can reference this, but you can't assign a value to it.

If you have some array destruction you want to perform you can reference this.myArrayName within your destroy method and free up whatever you're trying to release, but you can't just assign null to this to destroy an instance.

I suppose you could try something like this:

var foo = {
    // will nullify all properties/methods of foo on dispose
    dispose: function () { for (var key in this) this[key] = null; }
}

foo.dispose();

Pretty much as close as you can get to legally nullifying "this"...

Happy coding.

B

Call me old fashion, but:

foo = null;

I'm not sure why you're making this difficult. Javascript is a garbage collected language. All you have to do to allow something to be freed is to make sure there are no more references to it anywhere.

So, if you start with:

var obj = {
    data: "foo";
};

and now you want to get rid or "free" that object, all you have to do is clear the reference to it with:

obj = null;

Since there are no longer any references in your code to that data structure that you originally defined and assigned to obj , the garbage collector will free it.

An object cannot destroy itself (because other things may have references to it). You allow it to be freed by removing all references to it. An object can clear out it's own references to other things, though that is generally not required as removing all references to the object itself will also take care of the references it holds (with the exception of some bugs with circular references between JS and the DOM in certain older browsers - particular IE).

One time when you might explicitly "delete" something is if you have a property on an object that you wish to remove. So, if you have:

var obj = {
    data: "foo",
    count: 4
};

And you wish to remove the "data" property, you can do that with this:

delete obj.data;

of if the property/key was assigned programmatically via a variable like this:

var key = "xxx";
obj[key] = "foo";

you can remove that key with:

delete obj[key];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM