Javascript 一旦达到目的,对象是否可以在javascript中自动删除自身?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2304860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can an object automatically delete itself in javascript once it has achieved its purpose?
提问by Travis
I am wondering if it is possible for an object in javascript to delete itself once it has finished its task.
我想知道javascript中的对象是否有可能在完成任务后删除自己。
For example, I have the following object...
例如,我有以下对象...
var myObject = Object.create(baseObject);
myObject.init = function() {
/* do some stuff... */
delete this;
};
myObject.init();
Does this work? If not, is there another way?
这行得通吗?如果没有,还有其他方法吗?
回答by CMS
That wouldn't work, first because the thisvalue associated with an execution context is immutable.
这是行不通的,首先是因为this与执行上下文关联的值是不可变的。
You might now think that deleting myObject(by delete myObject;) might work, but that wouldn't do it either.
您现在可能认为删除myObject(by delete myObject;) 可能有效,但这也行不通。
Variables are really properties of the Variable Object, this object is not accessible by code, it is just in front of in the scope chain, where you do the variable declarations.
变量实际上是Variable Object 的属性,该对象不能通过代码访问,它就在作用域链的前面,您可以在这里进行变量声明。
The Variable statement, creates those properties with the { DontDelete }attribute, and that causes the deleteoperator to fail.
Variable 语句使用{ DontDelete }属性创建这些属性,这会导致delete运算符失败。
An option if you want to achieve this is to nullifyyour myObjectinstance, but that doesn't guarantees that another reference is still pointing to that object.
如果您想实现这一点,一个选项是使您的myObject实例无效,但这并不能保证另一个引用仍然指向该对象。
Recommended lectures:
推荐讲座:
回答by Ignacio Vazquez-Abrams
No. thisis just a local reference to the object so deleting it does not make the object not exist. There is no way for an object to self destruct in this manner. If you have large objects that you believe should be erased afterwards then you should look at using the Facade or Strategy patterns.
号this只是对对象的本地引用,因此删除它不会使对象不存在。对象无法以这种方式自毁。如果您认为以后应该删除大型对象,那么您应该考虑使用 Facade 或 Strategy 模式。
回答by Patrick
You could try
你可以试试
window.namespace.myObject = Object.create(baseObject);
namespace.myObject.init = function() {
/* do some stuff... */
delete window.namespace.myObject;
}
namespace.myObject.init();

