2014-01-23 53 views
1

我是全新的打字稿 - 有變量和範圍的問題。TypeScript傳遞變量

我有2個公共方法,一個需要一個字符串。 第一種方法從jQuery點擊函數中調用第二個方法(這意味着我不能再使用this.methodName了)。我試圖用邏輯方法修復範圍,但是TS抱怨:

提供的參數不匹配調用目標的任何簽名。 無法選擇「調用」表達式的重載。

public test1() { 
     //fix scope 
     var scopeFix =() => this.test2; 

     $("#test").click(function() { 
      //this.test2("blah"); 
      //^^^ This doesn't work because "this." is used by jquery 
      scopeFix("blah"); 
     }); 
    } 

    public test2(testString:string) { 
     alert(testString); 
    } 

我敢肯定這是愚蠢的東西(就像我混合JS和TS太多) - 任何想法?

+1

使用本地存儲到'你需要this'範圍的參考,http://jsfiddle.net/9DjGp/ – asawyer

+0

很近! 謝謝隊友。 – Richard

+0

當然,這是一個常見的問題。儘管與打字稿無關。打字稿錯誤是因爲'scopeFix'函數是返回一個函數的無參數函數,所以你的調用網站是錯誤的,它應該更像'fixScope()('blah');'' – asawyer

回答

2

在打字稿,你可以這樣做:

public test1() { 
    $("#test").click(() => { 
     this.test2("blah"); 
    }); 
} 

注意() => {}語法。爲了給你這是什麼做的一個想法,請查看編譯的JavaScript:

YourClass.prototype.test1 = function() { 
    var _this = this; 

    $("#test").click(function() { 
     _this.test2("blah"); 
    }); 
};