Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...