2011-10-10 38 views
2

我在對象的遊戲引擎中使用閉包。說這樣的:關閉中的JavaScript垃圾回收

var newSprite = function() { 
    var x = 0; 
    var y = 0; 
    var returnobj = { 
     getPos:function(){ 
      return [x,y]; 
     } 
    } 
    return returnobj; 
} 

這不是實際的代碼,但它說明了。我在scenegraph中有對象,如果我將場景圖中的對象設置爲null,那麼垃圾回收器會收集所有這些嗎?我需要將每個變量設置爲null嗎?

+0

如果您澄清了「場景圖中的對象」的含義,最好使用代碼,這將更容易回答。同樣,你的意思是「將每個變量設置爲null」。 – Domenic

+0

當每個對象被創建時,它被添加到數組以繪製到畫布。當我說「設置每個變量爲空」我的意思是; scenegraph [3] = null – Isaiah

回答

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. 
+0

而那些其他引用是可訪問的。 – jdigital

+0

如果我設置了returnobj,那麼返回所有內容,本身爲null? – Isaiah

+0

你能給出一些示例代碼的樣子嗎?請記住'returnobj'只是對內存結構的引用;如果其他人有一個引用結構的名稱,有時名字爲'returnobj',有時名爲'myOtherReferenceToTheSprite',那麼將'returnobj'設置爲'null'將不會爲你做任何事情。 – Domenic

0

是 - 一旦你的對象爲空,在封閉的引用不再訪問,並會被垃圾收集。如果沒有別的東西可以引用該對象內的東西。