Mar*_*ope 0 javascript stack-overflow recursion class stackpanel
我有以下代码示例来说明我的观点.当我在Vista上的IE8中加载它时,我收到错误"Stack Overfow at line:16"
如果我使用顶级函数(在testClass对象之外)递归,我可以在没有堆栈溢出的情况下递归数百万次.
为什么会这样?最后我只是实现了一个函数Que而不是使用递归,但对我来说没有意义,我想了解原因.
- 代码 -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">
<html>
<head>
<title>Recusion Test</title>
<body>
</body>
<script type="text/javascript">
function testClass() {
this.x = 15;
this.recurse = function() {
this.x--;
this.recurse();
}
}
var wtf = new testClass();
wtf.recurse();
alert('done');
</script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
您的递归语句没有终止条件,因此它将永远运行.
看来你想......
function testClass() {
this.x = 15;
this.recurse = function() {
if (this.x--)
this.recurse();
}
}
var wtf = new testClass();
wtf.recurse();
alert('done');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |