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);
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]().

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']();

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.