2012-04-09 49 views
0
class Example 
    constructor: -> 
    $.each [1, 2, 3], (key, value) -> 
     @test = value 
    return @test 
    render: -> 
    alert @test 

example = new Example() 
example.render()​​​​​​​​​​​​​​​​​​​​​​ 

我正在使用CoffeeScript(+ jQuery),這是一個類示例,我將在@test變量中獲取值3。但是這不會發生,你能幫助我嗎?CoffeeScript類變量

+0

構造函數不能返回任何東西。實例化類時總會返回該類的實例。與你的問題沒有任何關係,但我想我應該讓你知道。 – Sandro 2012-04-09 13:02:19

+0

糾正他人閱讀...構造函數*絕對可以*返回值;他們只需返回一個* object *(也就是說,沒有原始值,如數字或字符串)(參見:http://es5.github.io/#x13.2.2,步驟9和10) – ELLIOTTCABLE 2013-04-15 23:55:52

回答

3

這是一個範圍問題: $.each接受一個函數,它有它的範圍,因此,您this變量是不是你所期望的一個。

工作代碼:

class Example 
    constructor: -> 
    $.each [1, 2, 3], (key, value) => 
     @test = value 
    return @test 
    render: -> 
    alert @test 

example = new Example() 
example.render()​​​​​​​​​​​​​​​​​​​​​​ 

是什麼改變了?檢查$.each電話上的箭頭,現在它是一個胖箭頭。胖箭頭的作用就是設置一個_this變量,並在使用@...時使用它,使您的範圍成爲您期望的範圍。

檢查http://coffeescript.org關於「功能綁定」部分的更多詳細信息!