2013-03-17 62 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所以不要那么做远。