开发者

How to delete an object in Javascript crossbrowser

开发者 https://www.devze.com 2023-03-22 13:08 出处:网络
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 objec
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-h开发者_如何学Goand 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];
0

精彩评论

暂无评论...
验证码 换一张
取 消