本文實(shí)例分析了javascript針對(duì)不確定函數(shù)的執(zhí)行方法。分享給大家供大家參考,具體如下:
在javascript中,有時(shí)候只知道一個(gè)函數(shù)的名字,但并不確定該函數(shù)有沒(méi)有,如何判斷該函數(shù)是否存在,并執(zhí)行呢。一個(gè)方法是用eval() 執(zhí)行拼接的程序字符串,但可能帶來(lái)性能問(wèn)題。另一個(gè)方法是使用符號(hào)屬性的方式來(lái)訪問(wèn)函數(shù),因?yàn)楹瘮?shù)都是window對(duì)象的屬性。
利用window[函數(shù)名] 來(lái)代表該function對(duì)象,用window[函數(shù)名]()來(lái)執(zhí)行或調(diào)用該函數(shù)。
例子:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>新建網(wǎng)頁(yè) 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> 希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。















