Coffeescript/Javascript variable scope

混江龙づ霸主 提交于 2019-12-14 01:01:09

问题


I'm not really sure why i do not have access to the @date (this.date) variable from the context of the anonymous function defined in C.f()

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

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

Could someone comment on that?


回答1:


This is happening because inside the keydown event handler, the this value will not refer to your object, it will refer to the DOM element.

For that purpose, you can use => (the fat arrow), that will bind the handler's this value to the parent this:

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

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


来源:https://stackoverflow.com/questions/7062223/coffeescript-javascript-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!