javascript 元编程之如何不使用 eval,通过一个字符串来调用对应的函数
背景
// function we want to run
var fnstring = "runMe";
function runMe() {
// do stuff
}
实现 fnstring(),在 php 中可以使用 call_user_func()
,那么 js 中应该如何做呢?
比较死板的做法
// function we want to run
var fnstring = "runMe";
switch (fnstring) {
case "functionX": functionX(); break;
case "functionY": functionY(); break;
case "functionZ": functionZ(); break;
case "runMe": runMe(); break;
}
变通的方法
无参数
// function we want to run
var fnstring = "runMe";
// find object
var fn = window[fnstring];
// is object a function?
if (typeof fn === "function") fn();
有参数
// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];
// find object
var fn = window[fnstring];
// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);