tags:

views:

49

answers:

2

is it possible to call a dynamic method in javascript. ie suppose i have in my page 2 methods as such:

function id1_add()
{
  return 1;
}

function id2_add()
{
  return 2;
}

i also have this function:

function add()
{
  var s1='id1';

  s1+'_add()'; //???
}

is it possible to call for example id1_add() in such:

 s1+'_add()'; 

so the method call depends on a previous string?

+3  A: 

In the specific case of function declared in the global scope only, you can do

window[s1 + "_add"]();

Note this will not work for nested functions. This also relies on the global object being mapped to window, which is the case in all scriptable browsers.

Tim Down
+1 less awful than `eval`. But in any case, it's a code smell. An explicit lookup of names to functions might be preferable.
bobince
Yep. I lazily omitted the "are you sure you should be doing this?" bit.
Tim Down
@bobince: `eval` is not necessarily awful. It really depends on how you use it (see discussion in my answer).
nico
A: 

Aside from Tim's method you can also eval(s1+'_add()');.

However this method can be unsafe if not used correctly.

See http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil

A better option would be to have a function to which you pass a different parameter depending on what you want to do.

nico