简体   繁体   中英

Call function via string?

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);

如果是全局函数,则可以编写window[stringVar]()

您在全局范围内声明的函数将成为window对象的一部分,因此您应该可以调用此函数:

window['js_inject']();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM