2013-03-17 94 views
0

我剛剛開始使用Coffeescript並運行「Programming in CoffeeScript book」中介紹的示例。在While循環語法中傳遞匿名變量

在while循環部分,我很感興趣爲什麼要調用times函數必須聲明如下。

times = (number_of_times, callback) -> 
    index = 0 
    while index++ < number_of_times 
     callback(index) 
    return null 

times 5, (index) -> 
    console.log index 

我掙扎了一下,閱讀代碼,當我已經試過:

times (5, (index)) -> 
    console.log index 

它返回一個錯誤。 請你幫忙理解這段代碼嗎?

+0

請附上您在文章中提到的錯誤消息。 – 2013-03-17 16:52:53

+0

我不明白這個問題。請修正縮進 – Ven 2013-03-17 17:16:00

回答

1

標準函數定義的結構是這樣的:

name = (arg, ...) -> 
    body 

所以沒有太多說你times定義。因此,讓我們看看你的調用times

times 5, (index) -> 
    console.log index 

這一部分:

(index) -> 
    console.log index 

只是另一個函數的定義,但是這個人是匿名的。我們可以通過一個名爲功能幫助澄清事情重寫您的來電:

f = (index) -> console.log index 
times 5, f 

而且我們可以在可選的括號中填寫要真正拼出來:

f = (index) -> console.log(index) 
times(5, f) 

一旦一切都已經被打破,你應該看到5(index)在:

times 5, (index) -> 
    console.log index 

無關相互括號所以對它們進行分組:

times (5, (index)) -> 
    console.log index 

沒有意義。如果你想括號添加到times呼叫澄清結構(這是相當有用的,當回調函數是更長的時間),你需要知道兩件事情:

  1. 函數名和左括號各地之間沒有空間參數。如果有空格,那麼CoffeeScript會認爲你使用圓括號將分組在的參數列表中。
  2. 圓括號需要包圍整個參數列表幷包含回調函數的主體。

給,你會寫:

times(5, (index) -> 
    console.log index 
) 

或者是:

times(5, (index) -> console.log(index)) 

隨着console.log是一個非本地功能你甚至可以:

times(5, console.log) 

但那會給你一個TypeError in some browsers所以不要那麼做遠。