如何使用Coffeescript fat arrow在事件处理程序中引用父对象
大家好,我是Js和Coffeescript的新手,在下面的示例中,我觉得很难引用父对象的属性如何使用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方法的上下文
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:=>
将按照您期望的方式运行
演示:看看这个答案,讨论胖箭头。看看这个答案,讨论一下胖箭。塞