一旦达到目的,对象是否可以在javascript中自动删除自身? [英] Can an object automatically delete itself in javascript once it has achieved its purpose?

查看:122
本文介绍了一旦达到目的,对象是否可以在javascript中自动删除自身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道javascript中的对象是否有可能在完成任务后自行删除。

I am wondering if it is possible for an object in javascript to delete itself once it has finished its task.

例如,我有以下对象.. 。

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?

推荐答案

那不行,首先是因为 与执行上下文关联的此 值为 immutable

That wouldn't work, first because the this value associated with an execution context is immutable.

您现在可能认为删除 myObject (按删除myObject; )可能会有效,但也不会这样做。

You might now think that deleting myObject (by delete myObject;) might work, but that wouldn't do it either.

变量实际上是变量对象的属性,代码无法访问此对象,它位于范围链的前面,您可以在其中执行变量声明。

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语句使用 {DontDelete} 属性创建这些属性,这会导致 delete 运算符失败。

The Variable statement, creates those properties with the { DontDelete } attribute, and that causes the delete operator to fail.

如果你想实现这个目的,那么取消你的 myObject 实例,但这并不能保证另一个引用仍然是指针这个对象。

An option if you want to achieve this is to nullify your myObject instance, but that doesn't guarantees that another reference is still pointing to that object.

推荐讲座:


  • 了解删除

  • < a href =http://bclary.com/2004/11/07/#a-10.1.3 =noreferrer>变量实例化

  • Understanding delete
  • Variable instantiation

这篇关于一旦达到目的,对象是否可以在javascript中自动删除自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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