2016-11-24 12 views
1

私は、次の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クラスを呼び出すと、無限ループになります。

クラス全体で1つの変数しか作成できない方法はありますか? 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

[最大コールスタックサイズはエラー超過]の可能な重複(http://stackoverflow.com/questions/ 6095530/maximum-call-stack-size-exceeded-error) –

+0

これでも問題は解決しません – Techs

答えて

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; 
     } 
    } 
+0

これでも同じエラーが発生します – Techs

+0

@Techs初めて電話を設定することはできますか? –

+0

私はそれについて考えました。しかし、私はそれをどうやってできるのか考えられません – Techs

関連する問題