GAS中如何通过变量直接调用对应函数?替代多if分支
在Google Apps Script中通过变量调用函数的实现方法
当然可以用一行代码实现,推荐两种可靠方案:
方案1:函数映射对象(推荐,更安全)
先创建一个动作码与对应函数的映射对象,之后直接通过动作码索引调用函数:
// 定义动作-函数映射 const actionMap = { root: root, worlds: worlds, worldone: worldone, worldtwo: worldtwo }; // 一行代码调用(可加前置判断避免错误) if (!actionMap[thisActionCode]) throw new Error(`无效动作码:${thisActionCode}`); return actionMap[thisActionCode](e, thisCurrentUser, thisActionCode, veracity);
这种方式的好处是仅允许调用你明确指定的函数,避免误触全局环境中的其他函数,安全性更高,也更便于维护——后续新增动作只需在映射对象里加键值对即可。
方案2:直接调用全局函数(简洁但需注意安全)
如果你的响应函数都是全局函数,可直接通过globalThis对象索引调用:
// 一行代码调用(建议加类型判断) if (typeof globalThis[thisActionCode] !== 'function') throw new Error(`无效动作码:${thisActionCode}`); return globalThis[thisActionCode](e, thisCurrentUser, thisActionCode, veracity);
这种写法更简洁,但要确保thisActionCode的来源是可信的(比如仅由你的菜单系统生成,不会被外部篡改),否则可能存在调用未预期函数的风险。
内容的提问来源于stack exchange,提问作者Jukebox Jory
相关产品推荐
相关产品推荐

