根據字符串動態調用函數,常見於插件系統、命令分發、配置驅動邏輯。本文對比 eval、window[fnName]、Map/Object 映射、new Function 四種方案,分析安全性、性能、作用域、可維護性,給出最佳實踐建議。
| 方案 | 安全性 | 性能 | 作用域 | 可維護性 | 推薦度 |
|---|---|---|---|---|---|
| eval('fn()') | 極低(任意代碼執行) | 低(解析開銷) | 當前詞法作用域 | 差(字符串拼接難調試) | ❌ 禁用 |
| window[fnName]() | 中(僅全局函數) | 高 | 全局作用域 | 中(隱式依賴全局) | ⚠️ 受限場景 |
| obj[fnName]() / Map | 高(白名單控制) | 高 | 對象方法上下文 | 好(顯式註冊、可樹搖) | ✅ 首選 |
| new Function('return ' + fnName)() | 低(動態代碼) | 低 | 全局作用域 | 差 | ❌ 禁用 |
// 1. 定義命令映射表(可拆分模塊、按需加載)
const actions = {
save: function (data) { console.log('保存', data); return {ok: true}; },
delete: function (id) { console.log('刪除', id); return {ok: true}; },
export: function (format) { console.log('導出', format); return {ok: true}; }
};
// 2. 統一調用入口
function dispatch(actionName, ...args) {
const fn = actions[actionName];
if (typeof fn !== 'function') {
throw new Error('未知操作: ' + actionName);
}
return fn.apply(null, args); // 或 fn(...args)
}
// 3. 使用
dispatch('save', {id: 1, name: 'Test'});
dispatch('delete', 42);
// 4. 動態註冊(插件擴展)
function registerAction(name, fn) {
if (actions.hasOwnProperty(name)) {
console.warn('覆蓋現有 action:', name);
}
actions[name] = fn;
}
const CommandBus = {
_handlers: new Map(),
register(namespace, name, handler) {
const key = namespace + ':' + name;
this._handlers.set(key, handler);
},
execute(namespace, name, ...args) {
const handler = this._handlers.get(namespace + ':' + name);
if (!handler) throw new Error('Command not found: ' + namespace + ':' + name);
return handler(...args);
}
};
// 使用
CommandBus.register('user', 'create', (data) => api.post('/users', data));
CommandBus.execute('user', 'create', {name: 'Tom'});
Content-Security-Policy: script-src 'self' 會直接阻斷 eval。// 舊代碼
eval('this.' + method + '()');
// 遷移:提取方法到對象
const methods = {
init: this.init.bind(this),
refresh: this.refresh.bind(this),
destroy: this.destroy.bind(this)
};
function call(method) {
const fn = methods[method];
if (fn) fn();
else console.warn('No such method:', method);
}
async function loadAndExecute(modulePath, exportName, ...args) {
const mod = await import(modulePath); // 動態 import,返回 Module Namespace Object
const fn = mod[exportName];
if (typeof fn === 'function') return fn(...args);
throw new Error('Export not a function: ' + exportName);
}
// 使用
loadAndExecute('./commands/save.js', 'default', data);
堅持「顯式映射、拒絕 eval」,代碼更安全、可測試、可靜態分析、利於團隊協作。