javascript针对不确定函数的执行方法

javascript中,有时候只知道一个函数的名字,但并不确定该函数有没有,如何判断该函数是否存在,并执行呢。一个方法是用eval() 执行拼接的程序字符串,但可能带来性能问题。另一个方法是使用符号属性的方式来访问函数,因为函数都是window对象的属性。

利用window[函数名] 来代表该function对象,用window[函数名]()来执行或调用该函数。

例子:

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>新建网页 1</title> </head> <body> <script language="javascript"> function input1_onChange(){ alert('input1_onChage executed.'); } var objId = 'input1'; if(window[objId +'_onChange']){ alert('There is the funtion'); }else{ alert('There is not the funtion'); } if(window[objId+'_onChange'] && typeof(window[objId+'_onChange'])=='function'){ window[objId+'_onChange'](); } var fun = window[objId+'_onChange']; if(fun && typeof(fun)=='function'){ fun(); } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgzyzf.html