2013-02-18 103 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/