JS根据变量保存方法名并执行方法示例


复制代码 代码如下:

function a(){
alert("fun a()");
}
function b(){
alert("fun b()");
}
var methodName = "";
//method1
methodName = "a";
function method1(methodName){
//初始化this.func属性,
this.func = function(){};
try{
//这里用eval方法,把我们传进来的这个方法名所代表的方法当作一个对象来赋值给method1的func属性。
//如果找不到methodName这个对应的对象,则eval方法会抛异常
this.func = eval(methodName);
}catch(e){
alert(methodName+"()不存在!");
}
}
var c = new m(methodName);
c.func();

/**
* method2, 比较简洁
*/
methodName = "b";
function method2(methodName){
this.func = new Function(methodName+"();");
}
var c = new m(methodName);
try{
c.func();
}catch(e){
Ext.Msg.alert(methodName+"()不存在!");
}

« 
» 
快速导航

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