当你定义你的show函数时,@(AKA this) 实际上是window这样的
show: => console.log(@)
将绑定show到window. 问题是您只是在定义一个对象,所以没有任何东西可以绑定:您没有定义一个类,this所以window. 您可以App像这样明确引用:
App =
#...
show: -> alert(App.foo)
演示:http: //jsfiddle.net/ambiguous/3sRVh/
this.fooin会做正确的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: //jsfiddle.net/ambiguous/byatH/