如何使用CoffeeScript的脂肪箭头
问题描述:
您好我是新来的JS和的CoffeeScript指在事件处理程序的父对象,这里的情况,我觉得很难参照这是App
在下面的示例中,父对象的属性如何使用CoffeeScript的脂肪箭头
App =
init: ->
this.foo = 'bar'
this.bindEvent()
bindEvent: ->
$('#test').click(this.show)
show: ->
alert this.foo
App.init()
我觉得胖箭头可以做的伎俩,但一旦我在show
方法的上下文改为show: =>
,this
指的不是我想要 App
对象window对象。任何人都可以告诉我该怎么做对吗?
答
当你定义show
功能,@
(AKA this
)实际上是window
所以
show: => console.log(@)
将绑定show
到window
。问题在于你只是定义一个对象,所以没有任何东西可以绑定到:你没有定义类,所以this
是window
。你可以参考App
明确这样的:
App =
#...
show: -> alert(App.foo)
演示:http://jsfiddle.net/ambiguous/3sRVh/
的this.foo
在init
会做正确的事,因为说App.init()
树立预期this
。
您也可以手动挂钩所需this
:
bindEvent: ->
$('#test').click => @show()
# or
bindEvent: ->
_this = @ # JavaScript style
$('#test').click -> _this.show()
演示:http://jsfiddle.net/ambiguous/byL45/,http://jsfiddle.net/ambiguous/MT8fG/
或者你可以为你的应用程序创建一个类来代替:
class App
constructor: ->
@foo = 'bar'
@bindEvent()
bindEvent: ->
$('#test').click(@show)
show: =>
console.log(@foo)
new App
这样您的show: =>
将按照您的预期行事。
看看这个答案的脂肪箭头的讨论。 http://stackoverflow.com/questions/13184209/when-does-the-fat-arrow-bind-to-this-instance/13184211#13184211 se – robkuz 2013-02-18 07:45:01