Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an object automatically delete itself in javascript once it has achieved its purpose?

Tags:

javascript

oop

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?

like image 284
Travis Avatar asked Feb 21 '10 05:02

Travis


People also ask

How does delete work in JavaScript?

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

Can object be deleted?

Certain objects cannot be deleted via the API. To delete an object via the delete() call, its object must be configured as deletable (deletable is true ) . To determine whether a given object can be deleted, your client application can invoke the describeSObjects() call on the object and inspect its deletable property.

How do we delete the object property in JavaScript?

The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

Which function is used to delete the objects?

Explanation: The global delete operator is called to delete the objects that are not of class type. Class type includes class, union or struct. All objects of these types can be deleted using the global delete operator.


2 Answers

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

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.

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

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.

Recommended lectures:

  • Understanding delete
  • Variable instantiation
like image 161
Christian C. Salvadó Avatar answered Sep 23 '22 04:09

Christian C. Salvadó


No. this is 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.

like image 20
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 04:09

Ignacio Vazquez-Abrams