複製代碼代碼如下:
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+"()不存在!");
}