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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值