How to delete an object in Javascript crossbrowser

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 03:30:01

问题


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;} 

回答1:


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




回答2:


Call me old fashion, but:

foo = null;



回答3:


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];


来源:https://stackoverflow.com/questions/6794369/how-to-delete-an-object-in-javascript-crossbrowser

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