2012-11-17 22 views
15

我有這樣的打字稿代碼:如何從功能訪問類成員方法類的打字稿

module MyPage { 

    export class MyVm { 

     ToDo : string; 

     Load() { 
      //can access todo here by using this: 
      this.ToDo = "test"; 

      $.get("GetUrl", function (servertodos) { 
       //but how do I get to Todo here?? 
       this.ToDo(servertodos); //WRONG ToDo.. 
      }); 
     } 
    } 
} 

的問題是,如何訪問在$不用彷徨回調待辦事項成員字段?

回答

22

打字稿還支持箭頭功能保存詞法範圍。箭功能導致類似的代碼的Jakub的例子,但整潔,你不需要自己創建的變量和調整用量:

下面是用箭頭功能的例子:

$.get("GetUrl", (todos) => { 
    this.ToDo(todos); 
}); 
+2

一致認爲,這是更好的 – Flores

+3

這是我最喜歡Typescript的東西之一。 – Maverick

+0

如果在這個例子中同樣使用了'data',這可能會更加清晰 –

8

你這樣做在JavaScript中同樣的方式

export class MyVm { 
    ToDo : string; 

    Load() { 
     //can access todo here by using this: 
     this.ToDo = "test"; 
     var me = this; 

     $.get("GetUrl", function (todos) { 
      //but how do I get to Todo here?? 
      me.ToDo(todos); //WRONG ToDo.. 
     }); 
    } 
} 
+1

啊哈..我的缺乏JavaScript技巧 – Flores

+3

雖然這在技術上是正確的,但使用箭頭功能是更好的方法。 –

+0

此技術可用於其他類似場景。對我來說是一個正確的方向。 – HockeyJ