0

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?

2 Answers 2

3

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.

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

3 Comments

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

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.

Comments

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.