问题
I would like to know the correct way to completely dereference a JavaScript Object from memory. To ensure it's deletion without it dangling in memory, and that the garbage collector removes the object.
When I looked and this question Deleting Objects in JavaScript. It was explained that if you delete all the references of object, the GC will remove it from memory. I want to know how do I go about removing references from an object that has both methods and properties.
Suppose you have and object that was created by using function
, and the object has both methods and properties. Say it looks something like this:
function myObject(x, y) {
this.x = x;
this.y = y;
this.myMethod = function() {
// method code
}
}
var myInstance = new myObject(24, 42) // How to remove this completely?
Note: This is an example, I understand you can use prototype
for methods.
I know I can't just say delete myInstance
. So in this case to completely delete the object will I need to call delete
on all it's properties, and then call delete
on the instance, like so?
delete myInstance.x;
delete myInstance.y;
delete myInstance; // I'm not sure if this is necessary.
Would this work? Or do I need to also delete
it's methods (and if so how)?
Or perhaps there is a better and simpler way to do this?
回答1:
Javascript is a garbage collected language. It will clean up an object ONLY when there is no other code that has a reference to it. Those other references need to either go out of scope (and not be held by a closure) or you can set those other variables to something else so they don't point at your object. When there are no other variables with a reference to your object, it will be automatically taken care of by the garbage collector, including any properties it has (assuming none of those properties are themselves objects that something has a reference to - but even then the host object would be cleaned up and only the object in the property would continue to live on).
You cannot delete an object any other way in Javascript.
So, to remove the object created by this:
var myInstance = new myObject(24, 42) // How to remove this completely?
Just clear myInstance
like this:
myInstance = null;
You don't need to manually delete
the properties from myInstance
at all. If nobody has a reference to the mother object and none of the properties are objects that someone has a reference to, then the garbage collector will just clean everything up for you.
The delete
operator is primarily for removing properties from an object when you want the mother object to remain (e.g. when you just want to remove a property).
来源:https://stackoverflow.com/questions/25457518/how-to-correctly-dereference-then-delete-a-javascript-object