我可以在TypeScript中从类体内访问“类对象”

时间:2012-10-02 07:41:44

标签: typescript

我可以做一些类似于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;
})();

1 个答案:

答案 0 :(得分: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");
    }
}
<\ n>在TypeScript中,它将编译为:

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;
})();