Coffeescript / Javascript变量范围 [英] Coffeescript/Javascript variable scope

查看:124
本文介绍了Coffeescript / Javascript变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
    )

有人可以评论吗?

推荐答案

$ c> keydown 事件处理程序, this 值不会引用您的对象,它将引用DOM元素。

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.

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

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)
    )

这篇关于Coffeescript / Javascript变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆