Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  58] [ 4]  / answers: 1 / hits: 46168  / 15 Years ago, sun, february 21, 2010, 12:00:00

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?


More From » oop

 Answers
3

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:




[#97525] Tuesday, February 16, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathanaelzechariahl

Total Points: 745
Total Questions: 86
Total Answers: 103

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;