2011-11-26 72 views
3

我正在做一個簡單的JavaScript生命實現來試驗JavaScript 1.8的新功能,並且我使用此代碼得到了「InternalError:太多遞歸」,並且世界大小爲300 × 300:InternalError:遞歸太多

function LifeWorld(hDim, vDim) { 
    var data = let(that = this) Array.make(hDim, function(x) Array.make(vDim, function(y) new LifeCell(that, x, y))); 

    this.item = function(x, y) { 
     return (data[x] && data[x][y]) || null; 
    }; 

    this.draw = function(g) { 
     g.fillRect(0, 0, this.scale, this.scale); 
    }; 

    this.scale = 5; 
    this.offsetX = 0; 
    this.offsetY = 0; 

    // Finally, initialize all the cells and let them recognize their neighbours: 
    try { 
     for(let i = 0; i < ARRAY_SIZE * ARRAY_SIZE; i++) { 
      this.item(i/ARRAY_SIZE | 0, i % ARRAY_SIZE).init(); 
     } 
    } catch(e) { 
     alert(e); 
    } 
} 

function LifeCell(world, x, y) { 
    var ul, u, ur, 
     l,  r, 
     bl, b, br; 

    Object.defineProperties(this, { 
     world: { 
      get: function() { 
       return this.world; 
      } 
     }, 
     x: { 
      get: function() { 
       return this.x; 
      } 
     }, 
     y: { 
      get: function() { 
       return this.y; 
      } 
     } 
    }); 

    this.init = function() { 
     alert('Init ' + x + ', ' + y); 
     [ul, u, ur, 
     l,  r, 
     bl, b, br] = [world.item(this.x - 1, this.y - 1), world.item(this.x, this.y - 1), world.item(this.x + 1, this.y - 1), 
         world.item(this.x - 1, this.y),  world.item(this.x, this.y),  world.item(this.x + 1, this.y), 
         world.item(this.x - 1, this.y + 1), world.item(this.x, this.y + 1), world.item(this.x + 1, this.y + 1)]; 
     delete this.init; 
    }; 
} 

我得到一個警報,「初始化0,0」,所以在初始化之前一切正常,但後來我得到的異常信息。看起來它必須與world.item有關,但我不知道如何返回一些東西。

我無法使用Firebug進行調試,因爲這段代碼顯然會使Firefox崩潰。任何人都可以弄清楚這裏有什麼問題嗎?

回答

7

你的遞歸從這段代碼來:

x: { 
    get: function() { 
     return this.x; 
    } 
}, 

您傳回吸本身,這將返回吸氣劑本身,等等,這導致無限遞歸。對於你所有的獲得者來說似乎都是這樣。出於這個原因,放棄getter的想法可能會更好,因爲他們可能會導致這樣的挫敗感。

http://jsfiddle.net/8hVwb/

+0

發現了這一點已經喜歡5秒我張貼的問題後。哎呀。哦,我會接受這個。 – Ryan