我不太确定为什么我无法从 C.f() 中定义的匿名函数的上下文访问 @date (this.date) 变量
class C
constructor: () ->
@date = new Date()
f: () ->
$(document).keydown( (e) ->
alert(@date)
)
有人可以对此发表评论吗?
最佳答案
发生这种情况是因为在 keydown
事件处理程序中,this
值不会引用您的对象,而是引用 DOM 元素。
为此,您可以使用 =>
(fat arrow),它将处理程序的 this
值绑定(bind)到父 this
:
class C
constructor: () ->
@date = new Date()
f: () ->
$(document).keydown( (e) =>
alert(@date)
)
关于javascript - Coffeescript/Javascript 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7062223/