5

Possible Duplicate:
Dynamic object property name

I have a function that I need to call based on a user inputted data.

So for example, I have:

models.cat
models.dog

Now, I want to be able to call models.[my_str] where my_str = "snake". So the computer would think it is trying to execute models.snake. Is there a way to do this in javascript or better yet coffeescript?

2
  • How about models.prototype[my_str]() Commented Jan 16, 2013 at 22:21
  • 2
    models[my_str]() should work, yes? Commented Jan 16, 2013 at 22:23

1 Answer 1

14

You should be able to call it like so:

models[my_str]();

This should work in both Javascript and Coffeescript.

Sign up to request clarification or add additional context in comments.

2 Comments

perfect. Works like a charm
You could also do models[my_str].call() which does the same thing, just has a different feel to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.