我有以下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;
}
由于
答案 0 :(得分:1)
您可以为此创建一个静态变量
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;
}
}