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
ThomasReggi
60.4k97 gold badges262 silver badges465 bronze badges
2 Answers 2
If it's a global function, you can write window[stringVar]().
answered Sep 12, 2011 at 22:58
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
GolezTrol
116k19 gold badges186 silver badges215 bronze badges
Comments
lang-js
eval(myString)? Where mymyString = 'js_inject()'. It might be simplistic, but that should work.eval