如何在Javascript跨浏览器中删除对象 [英] How to delete an object in Javascript crossbrowser

查看:114
本文介绍了如何在Javascript跨浏览器中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

obj.destroy();

这在Chrome中有效,但是由于某些原因,firefox抛出了引用此错误.有没有更好的方法可以在方法中杀死该对象?

错误:

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

解决方案

不确定Chrome为什么支持它,但是您不能为此指定值.您可以引用它,但不能为其分配值.

如果要执行一些数组销毁操作,可以在destroy方法中引用this.myArrayName并释放要释放的任何内容,但是不能仅仅为此分配null来销毁实例. /p>

我想您可以尝试这样的事情:

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

foo.dispose();

法律上将"this"作废的可能性就差不多了.

快乐的编码.

B

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

这篇关于如何在Javascript跨浏览器中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆