我可以从 TypeScript 中的类主体中访问"class object"吗



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

如果你写这个,看看你的例子:

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

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

相关内容

  • 没有找到相关文章

最新更新