Does javascript Garbage Collector dispose global variables?
I'm confused about this since I've seen several different comments. I'm reading a javascript book where it mentions that setting global variables to null is good practice (assuming there are no other references) and the GC reclaims memory for this variable on it's next sweep. I've seen other comments that say global variables are never disposed by the GC.
Also when programming javascript in a OOP structure, what happens if I have something like this (where game is in the global context):
var game = {};
game.level = 0;
game.hero = new hero();
//do stuff
game.hero = null;
Since hero lives inside an object which is stored in game, which is in a global context, If I set for instance hero to null, would this be disposed by the GC?
Global variables are never disposed of by the GC in the sense that a global variable will still exist. Setting it to null
will allow the memory that it references to be collected, however.
Eg
Before:
global -> {nothingness}
After:
global -> var a -> object { foo: "bar" }
Set a
to null
:
global -> var a -> null
Here, the memory used by the object will be eligible for collection. The variable a
still exists though, and it simply references null
.
The statement that global variables are never collected is slightly misleading. It might be more accurate to say that any memory that is traceable back to the global context is not currently eligible for collection.
In answer to your question, yes - the hero object will be eligible for collection, because its indirect connection to the global context has been severed.
链接地址: http://www.djcxy.com/p/27186.html上一篇: 在javascript中从内存中删除对象