javascript 不确定的函数的执行

来源:互联网 发布:比较好玩的java游戏 编辑:程序博客网 时间:2024/06/14 00:33

在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>