scatman
scatman

Reputation: 14555

calling a dynamic function in javascript

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?

Upvotes: 0

Views: 531

Answers (2)

Tim Down
Tim Down

Reputation: 324547

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.

Upvotes: 3

nico
nico

Reputation: 51640

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

However this method can be unsafe if not used correctly.

See When is JavaScript's 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.

Upvotes: -1

Related Questions