我有以下 JavaScript 类:
class TrieNode
{
constructor()
{
switch(arguments.length)
{
case 0 : this.constructorNoParam();
break;
case 1 : this.constructorOneParam(arguments[0]);
break;
}
}
constructorOneParam(c)
{
this.children=new TrieNode();
this.c = c;
this.isLeaf;
}
constructorNoParam()
{
this.children = new TrieNode();
this.c;
this.isLeaf;
}
}
我收到此错误的原因是每次创建 children
变量时,构造函数都会创建 TrieNode 类的另一个实例并导致无限循环。
有没有一种方法可以为整个类创建一个变量?我必须将它放在构造函数中,因为在 JavaScript 类中,变量只能在函数内部创建。
基本上,我想要在java中实现的目标如下:
public class TrieNode {
public char c;
TrieNode children = new TrieNode();
public boolean isLeaf;
public TrieNode() {}
public TrieNode(char c){
this.c = c;
}
谢谢
最佳答案
您可以为此创建一个静态变量,
class TrieNode {
constructor(time) {
if(time === "1") return;
switch(arguments.length) {
case 0 : this.constructorNoParam();
break;
case 1 : this.constructorOneParam(arguments[0]);
break;
}
}
constructorOneParam(c) {
this.children= TrieNode.children;
this.c = c;
this.isLeaf;
}
constructorNoParam() {
this.children = TrieNode.children;
this.c;
this.isLeaf;
}
}
TrieNode.children = new TrieNode("1");
// Now the code wont fall into a recursive loop
var x = new TrieNode();
var y = new TrieNode("foo", "bar");
并为首次设置创建一个配置。
<小时/>如果您想要子级的新实例,您也可以像下面这样做,
class TrieNode {
constructor(time) {
if(time === "1") return;
switch(arguments.length) {
case 0 : this.constructorNoParam();
break;
case 1 : this.constructorOneParam(arguments[0]);
break;
}
}
constructorOneParam(c) {
this.children= new TrieNode("1");
this.c = c;
this.isLeaf;
}
constructorNoParam() {
this.children = new TrieNode("1");
this.c;
this.isLeaf;
}
}
关于javascript - 超出最大调用堆栈大小 - 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40784628/