Reputation: 13209
is there a way to know when an object will be disposed by GC?
My object (call it A) write some variables in a global array-object, so when the object will be garbaged its own variable will stay in the global array-object, taking up memory.
ps. i have numerous objects A and i prefer to not call "manually" a method to free my global array-object.
This is my situation:
var global_array=[];
function A(x){
global_array.push({who:"A", what:x, id:A.instance++});
this.x=x;
}
A.instance=0;
A.prototype.useIt=function(){
return this.x*2;
}
//will be created an A object and will be garbaged after use by GC
function test(){
var a=new A(10);
var y=a.useIt();
}
test();
//i will never use <a> object again, but global_array hold {who:"A", what:10, id:0)}
DO NOT WANT
A.prototype.dispose=function(){
// free global_array at the correct index
}
Thanks.
Upvotes: 0
Views: 2300
Reputation: 1325
And what about clearing it from globla_array at the end of test method? As you are saying it won't be used anymore, it will be safe to clear that info.
EDIT: In response to your comment (as I think I can't get it clearly stated), let's asume you can get to know when object A is gc:
function objectGetGC(sender)
{
// You still have to implement here how to clear global_array from object data
// javascript won't know how to do it on its own.
}
If global_array holds a reference to object A, instead of only data, it won't be gc...
Hope that now is a bit clear what I mean.
Upvotes: 0
Reputation: 324627
I'm not exactly sure what the question is, but I can tell you this:
You can't tell exactly when an object will be garbage collected
An object cannot be garbage collected until all references to it have been deleted, so keeping a reference to an object in an array stored in a global variable will ensure that it isn't garbage collected until the page unloads.
Upvotes: 2