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


本文实例分析了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> 

希望本文所述对大家JavaScript程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3