0

I have a string variable js_inject and I am looking for a way to call the js_inject() function via the string. Is there any way to do this other than the example below? I am really looking to do this without conditionals.

var myString = 'js_inject';
moderator(stringVar){
 if(stringVar == 'js_inject'){
 js_inject();
 }
}
moderator(myString);
asked Sep 12, 2011 at 22:56
6
  • Have you try eval(myString)? Where my myString = 'js_inject()'. It might be simplistic, but that should work. Commented Sep 12, 2011 at 23:00
  • Except eval is evil. A script kiddy could very well alter this javascript code and kill his own browser... Commented Sep 12, 2011 at 23:03
  • @GolezTrol A script kiddy could very well alter this javascript code and kill his own browser ... looks like a strong argument in favor of eval Commented Sep 12, 2011 at 23:07
  • Always great to see this question. Again. And again. 496961, 359788, 912596, 1451145, 1144297, .... :-) Commented Sep 12, 2011 at 23:08
  • possible duplicate of How do I call a JavaScript function name using a string? Commented Sep 12, 2011 at 23:40

2 Answers 2

2

If it's a global function, you can write window[stringVar]().

answered Sep 12, 2011 at 22:58
Sign up to request clarification or add additional context in comments.

Comments

2

A function you declare in the global scope becomes part of the window object, so you should be able to call this:

window['js_inject']();
answered Sep 12, 2011 at 22:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.