如何使用Coffeescript fat arrow在事件处理程序中引用父对象

如何使用Coffeescript fat arrow在事件处理程序中引用父对象,coffeescript,arrow-functions,Coffeescript,Arrow Functions,大家好,我是Js和Coffeescript的新手,在下面的示例中,我觉得很难引用父对象的属性App App = init: -> this.foo = 'bar' this.bindEvent() bindEvent: -> $('#test').click(this.show) show: -> alert this.foo App.init() 我认为胖箭头可能会起作用,但一旦我更改为show:=>,在show方法的上下文

大家好,我是Js和Coffeescript的新手,在下面的示例中,我觉得很难引用父对象的属性
App

App =
  init: ->
    this.foo = 'bar'
    this.bindEvent()
  bindEvent: ->  
    $('#test').click(this.show)
  show: ->
    alert this.foo

App.init()
我认为胖箭头可能会起作用,但一旦我更改为
show:=>
show
方法的上下文中,此
指的是窗口对象,而不是我想要的
App
对象 . 谁能告诉我怎么做才对


当您定义
显示
功能时,
@
(又称
)实际上是
窗口

show: => console.log(@)
显示
绑定到
窗口
。问题在于,您只是定义了一个对象,因此没有任何东西可绑定:您没有定义一个类,因此
this
window
。您可以这样明确地引用
App

App =
  #...
  show: -> alert(App.foo)
演示:

init
中的
this.foo
将做正确的事情,因为说
App.init()
将设置预期的
this

您还可以手动连接所需的

bindEvent: ->
  $('#test').click => @show()

# or
bindEvent: ->
  _this = @ # JavaScript style
  $('#test').click -> _this.show()
演示:

或者您可以为您的应用程序创建一个类:

class App
  constructor: ->
    @foo = 'bar'
    @bindEvent()
  bindEvent: ->  
    $('#test').click(@show)
  show: =>
    console.log(@foo)

new App
这样,您的
show:=>
将按照您期望的方式运行


演示:

当您定义
show
函数时,
@
(又称
)实际上是
窗口

show: => console.log(@)
显示
绑定到
窗口
。问题在于,您只是定义了一个对象,因此没有任何东西可绑定:您没有定义一个类,因此
this
window
。您可以这样明确地引用
App

App =
  #...
  show: -> alert(App.foo)
演示:

init
中的
this.foo
将做正确的事情,因为说
App.init()
将设置预期的
this

您还可以手动连接所需的

bindEvent: ->
  $('#test').click => @show()

# or
bindEvent: ->
  _this = @ # JavaScript style
  $('#test').click -> _this.show()
演示:

或者您可以为您的应用程序创建一个类:

class App
  constructor: ->
    @foo = 'bar'
    @bindEvent()
  bindEvent: ->  
    $('#test').click(@show)
  show: =>
    console.log(@foo)

new App
这样,您的
show:=>
将按照您期望的方式运行


演示:

看看这个答案,讨论胖箭头。看看这个答案,讨论一下胖箭。塞