6

我正在制作一个简单的 JavaScript Life 实现来试验 JavaScript 1.8 的新功能,并且使用此代码得到“InternalError: too much recursion”,世界大小为 300×300:

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;
    };
}

我收到一个警报“Init 0, 0”,因此初始化之前的一切都正常工作,但随后我收到异常消息。看起来它必须与 相关world.item,但我不知道如何 -world.item只是返回一些东西。

我也无法使用 Firebug 进行调试,因为这段代码显然会使 Firefox 崩溃。谁能弄清楚这里出了什么问题?

4

1 回答 1

12

您的递归来自这段代码:

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

您正在返回 getter 本身,这将返回 getter 本身等,这会导致无休止的递归。您的所有吸气剂似乎都是这种情况。出于这个原因,最好放弃 getter 的想法,因为它们会导致这样的挫败感。

http://jsfiddle.net/8hVwb/

于 2011-11-26T21:22:41.553 回答