1

I want this to work:

I have defined a function:

function callback_1() {
 // Do something
}

I have a callback string that defines a callback:

var functionString = 'callback_' + 1 + '()';

I want to make that string actually call the function callback_1 How do I do that?

3
  • Will eval be sandboxed? I mean can I the defined function be outside eval context? Commented Sep 21, 2012 at 11:49
  • 1
    have a look at eval, but then try to figure out how you don't need it Commented Sep 21, 2012 at 11:49
  • 1
    NOO "eval()" is EVIL, the only time you had (not have, had) to use it was when parsing JSON back in the days. I've not seen any situation where eval was the only solution since... Commented Sep 21, 2012 at 12:03

2 Answers 2

6

As your functionString is in fact mainly a function's name, you can do that

window['callback_' + 1]();

This is much secure than eval as it only executes a function you yet have.

If you want to use the functionString you have (with its "()" at the end), you can use

window[functionString.slice(0, -2)]();
Sign up to request clarification or add additional context in comments.

1 Comment

Tried this and it works. Though in the string we need to remove ().
0

Try this: it is working for me

        eval(functionString);

5 Comments

Will eval be sandboxed? I mean can the defined function be outside eval context?
remember that in most cases, eval is evil :). dystroy answer is the one to go
@VladBalmos theres no reason this answer should be downvoted. If you like one answer over another then vote up the one you like.
@qwertymk: in this case, the answer can produce potentially harmful code, if the eval-string is based on user input or an ajax response. potentially dangerous code is a valid reason for down-voting, says the FAQ
@qwertymk what makes you think I down voted? Regardless, I am entitled to up / down vote based on the quality of the answer. See Elias comment on why it may be down voted

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.