有些情境下我們手上只有一個字串,例如 "a",卻需要呼叫對應的函式。以下示範兩種常見做法。
把方法名交給 eval,讓它回傳該名稱所對應的函式物件,再存進 func 屬性;若名稱不存在,eval 會丟出例外,可用 try/catch 攔下:
function a() { alert("fun a()"); }
function b() { alert("fun b()"); }
function method1(methodName) {
this.func = function () {};
try {
this.func = eval(methodName);
} catch (e) {
alert(methodName + "()不存在!");
}
}
var c = new method1("a");
c.func();
把呼叫語句拼成字串交給 Function,寫法更精簡,錯誤會在實際執行時才浮現:
function method2(methodName) {
this.func = new Function(methodName + "();");
}
var c = new method2("b");
try { c.func(); } catch (e) { alert(methodName + "()不存在!"); }
eval 與 Function 都會執行字串中的程式碼,若字串來源可能包含使用者輸入,就等於開了一個程式碼注入的入口,這是必須避免的風險。更值得推薦的方式是查表:把函式收進一個物件對應表,再用我想要的名稱當索引取出,既安全又不必解析字串:
var registry = { a: a, b: b };
if (typeof registry[name] === 'function') { registry[name](); }
另外,原範例中的 m 與 method1/method2 名稱不一致,實際執行時會出現找不到 m 的錯誤,複製使用時記得對齊命名。