Coffeescript/Javascript变量范围

Jul*_*usz 5 javascript coffeescript

我不确定为什么我无法从Cf()中定义的匿名函数的上下文访问@date(this.date)变量

class C
  constructor: () ->
    @date = new Date()

  f: () ->
    $(document).keydown( (e) ->
      alert(@date)
    )
Run Code Online (Sandbox Code Playgroud)

有人会对此发表评论吗?

CMS*_*CMS 9

发生这种情况是因为在keydown事件处理程序中,this值不会引用您的对象,它将引用DOM元素.

为此,您可以使用=>(胖箭头)将处理程序的this值绑定到父级this:

class C
  constructor: () ->
    @date = new Date()

  f: () ->
    $(document).keydown( (e) =>
      alert(@date)
    )
Run Code Online (Sandbox Code Playgroud)