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

JavascriptOop

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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:

Solution 2 - Javascript

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.

Solution 3 - Javascript

You could try

window.namespace.myObject = Object.create(baseObject);

namespace.myObject.init = function() {

   /* do some stuff... */

   delete window.namespace.myObject;

}

namespace.myObject.init();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTravisView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - JavascriptPatrickView Answer on Stackoverflow