2012-10-26 25 views
4

我怎麼想,使這項工作:「this」在TypeScript中的方法調用?

class TestClass { 

    doMethod1 (arg1, arg2, cb) 
    { 
     this.doMethod2(arg1, arg2, function (result){cb (result)}); 
    } 

    doMethod2 (arg1, arg2, cb) { 
     this.doMethod3(arg1, arg2, function(result){cb (result)}); 
    } 

    doMethod3 (arg1, arg2, cb) { 
     var result = arg1 + arg2; 
     cb(result); 
    } 
} 

測試=新識別TestClass;

test.doMethod3(1,1,cb); test.doMethod2(1,1,cb);

這兩個工作。

test.doMethod1(1,1,cb);

編輯:其實,它確實工作。

我得到了周圍相關的詞彙範圍的問題,通過使用「胖箭頭」語法:

doMethod1 (arg1, arg2, cb) 
    { 
     this.doMethod2(arg1, arg2, (result) => {cb (result)}); 
    } 

確保了「這個」在doMethod1是一樣的「本」,在匿名的回調函數。

回答

9

要在TypeScript中保留this的詞彙範圍,請使用箭頭函數表達式。

它們在TypeScript語言規範的4.9.2節中定義。

ArrowFormalParameters => { return AssignmentExpression ; } 

哪些代碼可以看起來像:

() => { alert(this.arg1); } 
相關問題