1

我有一个对象文字,用于对方法进行分组。我希望能够轻松调用一整组方法,如下所示:

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"

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

4

1 回答 1

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"
于 2012-09-04T04:21:09.227 回答