2016-11-23 49 views
0

我在JavaScript中創建的類如下外部函數的值:內部函數變量失敗「這個」

class TreeMatching 
{ 
     constructor() 
     { 
      this.thresholdPoints=0; 
      this.neighborWeight = 0.4; 
      this.totalFrequency = 0.0; 
      this.listSeq = []; 
      this.listFreq = []; 
      this.mapScore = new Object(); 
      this.tree = new Trie(); 
     } 

     createTree() 
     { 
      var list_Dictionary; 
      var loadWordList = $.get("../wordFrequencyTop5000.txt", function(data) 
      { 
       list_Dictionary = data.split("\n"); 
      }); 

      loadWordList.done(function() 
      { 
       for(var i=0;i<list_Dictionary.length;i++) 
       { 
        var string = list_Dictionary[i]; 
        this.tree.insert(string); //<-- Cannot read property 'insert' of undefined 
       } 
      }); 

     } 
} 

這是應該調用insert方法在類Trie樹如下:

class Trie 
{ 
     constructor() 
     { 
      this.count=1; 
      this.root = new TrieNode(); 
     } 

     insert(word) 
     { 
      var children = new Object(); 

      for(var i=0; i<word.length(); i++){ 
       var c = word.charAt(i); 

       var t; 
       if(children[c]){ 
         t = children[c]; 
       }else{ 
        t = new TrieNode(c); 
        children.put(c, t); 
       } 

       children = t.children; 

       //set leaf node 
       if(i==word.length()-1) 
        t.isLeaf = true; 
      } 
     } 
} 

但是,標有錯誤的代碼行(外部函數的此值)不具有屬性tree,mapScore等。

有沒有一種方法可以從內部回調函數中訪問這些值?

感謝

回答

1

look at 'this' - 你必須定義本地變量保持提及「本」裏面調用,如鏈接描述。

createTree() 
     { 
      var self = this; 
      var list_Dictionary; 
      var loadWordList = $.get("../wordFrequencyTop5000.txt", function(data) 
      { 
       list_Dictionary = data.split("\n"); 
      }); 

      loadWordList.done(function() 
      { 
       for(var i=0;i<list_Dictionary.length;i++) 
       { 
        var string = list_Dictionary[i]; 
        self.tree.insert(string); //<-- Now you should be able to do it 
       } 
      }); 

     } 
+0

謝謝!有用。 – Techs

0

'這個'在內部匿名有不同的範圍。嘗試使用JS中可以訪問函數調用者作用域的更接近的優點。

var that = this; 
loadWordList.done(function() { 
    for(var i=0;i<list_Dictionary.length;i++) 
    { 
     var string = list_Dictionary[i]; 
     that.tree.insert(string); // 'that' will hold 'this' in the right scope 
    } 
}); 
+0

感謝您的幫助 – Techs

0

內loadWordlist.done匿名函數創建了一個具有新的上下文有新的範圍。

,如果你想保留舊的背景下,你可以使用ES2015箭頭功能:

loadWordList.done(() => { 
    //code here 
); 

或使內部createTree(一個VAR)是這樣的:

var that = this; 

然後loadWordList內回調你可以參考正確的上下文使用:

that.tree.insert(string); 

我個人比較喜歡箭牌fu因爲'那個'是var name的糟糕選擇。而且由於您使用ES2015類瀏覽器支持不成問題。

+0

謝謝!它正在工作 – Techs