javascript 内部错误:递归过多
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8281682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
InternalError: Too much recursion
提问by Ry-
I'm making a simple JavaScript Life implementation to experiment with JavaScript 1.8's new features, and I'm getting an "InternalError: too much recursion" using this code, and a world size of 300×300:
我正在制作一个简单的 JavaScript Life 实现来试验 JavaScript 1.8 的新功能,使用此代码时出现“内部错误:递归过多”,世界大小为 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;
};
}
I get one alert, "Init 0, 0," so everything before the initialization works correctly, but then I get the exception message. It looks like it must have something to do with world.item
, but I don't know how — world.item
just returns something.
我收到一个警报,“Init 0, 0”,所以初始化之前的所有内容都可以正常工作,但随后我收到了异常消息。看起来它一定与world.item
,但我不知道如何 -world.item
只是返回一些东西。
I can't debug using Firebug, either, because this code apparently makes it crash Firefox. Can anyone figure out what's going wrong here?
我也无法使用 Firebug 进行调试,因为这段代码显然会使 Firefox 崩溃。谁能弄清楚这里出了什么问题?
回答by pimvdb
Your recursion is coming from this piece of code:
你的递归来自这段代码:
x: {
get: function() {
return this.x;
}
},
You're returning the getter itself, which will return the getter itself, etc, which causes an endless recursion. It seems to be the case for all your getters. For this reason it might be better to drop the idea of getters as they can cause frustration like this.
您正在返回 getter 本身,这将返回 getter 本身等,这会导致无休止的递归。您所有的吸气剂似乎都是这种情况。出于这个原因,最好放弃 getter 的想法,因为它们会导致像这样的挫折。