我只是想知道我怎样才能让它工作?
尝试在单击时引用方法
class C
@f: () ->
alert 'works'
null
constructor: () ->
console.log @f # why is this undefined?
document.onclick = @f
new C()
我只是想知道我怎样才能让它工作?
尝试在单击时引用方法
class C
@f: () ->
alert 'works'
null
constructor: () ->
console.log @f # why is this undefined?
document.onclick = @f
new C()
这是因为@f
编译this.f
为this
构造函数本身。
要访问类方法f
,您必须编写C.f
:
class C
@f: () ->
alert 'works'
null
constructor: () ->
console.log C.f
document.onclick = C.f
我假设您想绑定实例方法而不是类方法
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()