Javascript 超过最大调用堆栈大小-无限循环

Javascript 超过最大调用堆栈大小-无限循环,javascript,java,jquery,class,infinite-loop,Javascript,Java,Jquery,Class,Infinite Loop,我有以下JavaScript类: class TrieNode { constructor() { switch(arguments.length) { case 0 : this.constructorNoParam(); break; case 1 : this.constructorOneP

我有以下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;
        }
    }
我得到这个错误的原因是,每次我创建
子变量
时,构造函数都会创建Trinode类的另一个实例,并导致无限循环

有没有一种方法可以只为整个类创建一个变量?我必须把它放在构造函数中,因为在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;
      }
    }

可能的重复仍然不能解决我的问题issue@Techs你能区分第一次通话的设置吗?我考虑过了。但我想不出一个可能的方法,我怎么能做到这一点补充了一个解释,我想达到什么样的目标Java@Techs你没看到我答案的更新版本吗?这会解决你的问题。对不起,我没注意到!是的,它在工作:)谢谢