2016-11-24 41 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類並導致無限循環。

有沒有一種方法可以爲整個班級創建一個變量?我不得不把它放在構造函數中,因爲在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

相關問題