2012-10-02 12 views
2

我可以做一些類似的CoffeeScript和Ruby的東西在那裏我可以創建類 - 「宏」我可以從類主體中訪問「類對象」的打字稿

class A 
    # events adds the class method "listenTo" to the class (not to the prototype) 
    # listenTo will make all instances of A a listener to the given Event 
    events @ 

    # this will register instances of A to listen for SomeEvents 
    # the event broker (not here in this code) will specifically look 
    # for a method called "onSomeEvent(event)" 
    @listenTo SomeEvent 

    # and then later 
    onSomeEvent: (event)-> #do what ever is needed 

這將創建下面的JavaScript代碼在你的榜樣

var A; 
A = (function() { 
    function A() {} 
    events(A); 
    A.listenTo(SomeEvent); 
    A.prototype.onSomeEvent = function(event) {}; 
    return A; 
})(); 
+0

'events'從哪裏來?我不知道它在哪裏定義。 –

+0

這只是一個示例代碼。問題很簡單:我可以訪問「類」對象而不用提到打印稿中顯式的類名(在本例中爲「A」) – robkuz

+0

@robertj是的,這就是'this'是爲了。 –

回答

2

看,如果你這樣寫:

function events(A:any) { 
    A.listenTo = function(arg:any){alert(arg);}; 
} 

class A { 
    public onSomeEvent(event:any) { 
     //do stuff 
    } 
    constructor { 
     events(A); 
     (<any>A).listenTo("SomeEvent"); 
    } 
} 
在打字稿

,它將COMP ile into:

function events(A) { 
    A.listenTo = function (arg) { 
     alert(arg); 
    }; 
} 
var A = (function() { 
    function A() { 
     events(A); 
     (A).listenTo("SomeEvent"); 
    } 
    A.prototype.onSomeEvent = function (event) { 
    }; 
    return A; 
})();