1

I have an object literal that I'm using to group methods. I'd like to be able to call a whole group of methods easily, like so:

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"

When I try this it doesn't seem to work. What am I missing / how should you go about looping through a group of methods like this?

1 Answer 1

1

for ... in compiles down to a for loop that assumes you are looping over an array - use for own ... of instead:

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"
Sign up to request clarification or add additional context in comments.

3 Comments

Getting TypeError: method is not a function. If I just do console.log method in the for loop it prints methodA, methodB
Mea culpa @Andrew - I've fixed it (for ... of enumerates keys not values).
Ah, I get it. I didn't realize you could call a method like you were accessing a hash property, but of course that's all it is, so why not! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.