闭包中的JavaScript垃圾收集

Isa*_*iah 2 javascript garbage-collection

我在我的游戏引擎中使用闭包来获取对象.说出类似的话:

var newSprite = function() {
   var x = 0;
   var y = 0;
   var returnobj = {
       getPos:function(){
          return [x,y];
       }
   }
   return returnobj;
}
Run Code Online (Sandbox Code Playgroud)

这不是实际的代码,但它很好地说明了.我有一个场景图中的对象,如果我将场景图中的对象设置为null,垃圾收集会收集所有这些吗?我必须将每个变量设置为null吗?

Dom*_*nic 5

除非:

  1. 其他人正在坚持对给定精灵的引用.
  2. 其他人正在坚持对该someSprite.getPos方法的引用.

例:

var sceneGraph = [newSprite(), newSprite(), newSprite()];
var gotYourSprite = sceneGraph[0];
var gotYourMethod = gotYourSprite.getPos;

sceneGraph = null;
// gotYourSprite is still available and is not GC'ed, but the other two are gone.
gotYourSprite = null;
// gotYourSprite is gone, but neither the method nor the private variables can be
// GC'ed because you still have gotYourMethod, which captured x and y.
gotYourMethod = null;
// Now everything will be GC'ed.
Run Code Online (Sandbox Code Playgroud)