0

我只是想知道我怎样才能让它工作?

尝试在单击时引用方法

class C

  @f: () ->
    alert 'works'
    null

  constructor: () ->
    console.log @f # why is this undefined?
    document.onclick = @f

new C()
4

2 回答 2

4

这是因为@f编译this.fthis构造函数本身。

要访问类方法f,您必须编写C.f

class C

    @f: () ->
        alert 'works'
        null

    constructor: () ->
        console.log C.f
        document.onclick = C.f
于 2013-02-13T09:57:33.803 回答
3

我假设您想绑定实例方法而不是类方法

class C
    #this defines a class method
    @f: () ->
        alert 'works'
        null

    #this is an instance method
    f: () ->
        alert 'works'
        null

    constructor: () ->
        console.log @f # why is this undefined?
        document.onclick = @f

 new C()
于 2013-02-13T10:00:16.903 回答