CoffeeScript循环方法

时间:2012-09-04 04:17:13

标签: javascript loops methods coffeescript

我有一个对象文字,我用它来分组方法。我希望能够轻松地调用一组方法,如下所示:

group =
  methodA: (str) ->
    console.log str + "from method A"

  methodB: (str) ->
    console.log str + "from method B"

for method in group
  method "hello"

# should log to console:
# "hello from method A"
# "hello from method B"

当我尝试这个时它似乎不起作用。我错过了什么/你应该如何循环这样的一组方法呢?

1 个答案:

答案 0 :(得分:1)

for ... in编译为for循环,假设您循环遍历数组 - 请改为使用for own ... of

group =
  methodA: (str) ->
    console.log str + "from method A"

  methodB: (str) ->
    console.log str + "from method B"

for own method of group
  group[method] "hello"