How to delete an object in Javascript crossbrowser

孤人 提交于 2019-12-06 16:55:10

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!