Coffeescript/Javascript变量作用域

5

我不太确定为什么在C.f()中定义的匿名函数的上下文中,我无法访问@date (this.date)变量。

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

  f: () ->
    $(document).keydown( (e) ->
      alert(@date)
    )

有人能评论一下这个吗?

1个回答

9
这是因为在keydown事件处理程序中,this值不会指向您的对象,而是指向DOM元素。
为此,你可以使用=>fat arrow),它将绑定处理程序的this值到父级this
class C
  constructor: () ->
    @date = new Date()

  f: () ->
    $(document).keydown( (e) =>
      alert(@date)
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接