2013-02-18 46 views
0

您好我是新来的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对象。任何人都可以告诉我该怎么做对吗?

http://jsfiddle.net/kZpHX/

+0

看看这个答案的脂肪箭头的讨论。 http://stackoverflow.com/questions/13184209/when-does-the-fat-arrow-bind-to-this-instance/13184211#13184211 se – robkuz 2013-02-18 07:45:01

回答

3

当你定义show功能,@(AKA this)实际上是window所以

show: => console.log(@) 

将绑定showwindow。问题在于你只是定义一个对象,所以没有任何东西可以绑定到:你没有定义类,所以thiswindow。你可以参考App明确这样的:

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

演示:http://jsfiddle.net/ambiguous/3sRVh/

this.fooinit会做正确的事,因为说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/