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?
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.
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.
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.
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.
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:
delete
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With