动态执行 javascript 函数

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>无标题文档</title>
<script>
//动态执行函数:  
function g1(){return 21;}
function g2(){return 22;}
function g3(){return 23;}
function g4(){return 24;}

function g(a){return a()};
function f(i) { return g(eval("g"+i)); } 

document.write(f(1)+";"); //21
document.write(f(2)+";"); //22
document.write(f(3)+";"); //23
document.write(f(4)+";"); //24
</script> 
</head>
 <body> 
 </body>

</html>


以下为改进后的,当函数没有定义时,返回: No Function!


<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>无标题文档</title>
<script>

//动态执行函数:  
function g1(){return 21;}
function g2(){return 22;}
function g3(){return 23;}
function g4(){return 24;}

function g(a){
return a();
};
function f(i) { try{return g(eval("g"+i+""));} catch(e){return "NoFunction!";};} 

document.write(f(0)+";"); //NoFunction!
document.write(f(1)+";"); //22
document.write(f(2)+";"); //24
document.write(f(3)+";"); //26
document.write(f(4)+";"); //28
</script> 
</head>
 <body> 
 </body>

</html>


动态执行函数时,不能像:

if(typeof(var1)=='undefined') alert('var1未定义');else alert('定义过了');
这样来检测 函数是否定义!!









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值