tags:

views:

56

answers:

4

How can I find and execute a function inside of an object based on a string parameter?

see the following example:

               var parameters = 'people';

                switch (parameters) {
                     case 'people':
                          people.initialize();
                          break;
                }

How can I remove the switch case statement in this scenario? Is it possible to call an object just by knowing the string name of the object?

A: 
function people() { alert('You called people().'); }
var parameters = 'people';
eval(parameters+'()');

That should give you an alert saying "You called people()."

jsumners
eval is inefficient, a pain to debug, and suffers from scoping issues. Avoid it whenever possible (which is almost always).
David Dorward
Eval makes that dangerous for the same reason SQL injection is a problem. Better to use David Dorward's approach.
ssokolow
I agree. [At least 7 more characters.]
jsumners
Okay, it's not the best solution, but it certainly isn't "not useful." Jeez.
jsumners
If the function that needs to be "found" is not a global, `eval` is the only solution.
MooGoo
A: 

You can always use eval...

klausbyskov
+3  A: 

Organize your objects…

var myObjects = {
    people: someObject,
    notPeople: someOtherObject
};
var parameters = 'people';
myObjects[parameters].initialize();

If you are playing with globals (don't play with globals) then you can get away with:

window[parameters].initialize();

… but organizing them in logical objects is a better bet.

David Dorward
+1  A: 

You can use eval.

Or you might want to use the "pattern factory" http://en.wikipedia.org/wiki/Factory_method_pattern

The object declares itself to the factory with a string. Once you have a string ask the factory to give you the object.

Loïc Février
Thanks, the factory pattern was very interesting and relevant.
Victor