javascript - 如何避免使用 eval 调用不同的函数
问题描述
我有这段代码,eval
因为我发现调用不同的工厂函数来进行不同的 Web 服务调用是最容易的。
我已经读过这样做的方式不安全且“适当”。好吧,我想不出也找不到更好的方法来满足我的需要。
我怎样才能改善通话?
vm.saveRecord = function() {
var service = '';
if(vm.valueTrue) {
service = vm.otherValue ? 'function1' : 'function2';
} else {
service = vm.otherValue ? 'function3' : 'function4';
}
eval(service).callEndPoint(param1, param2).then(
function successCallback(response) {
if(response) {
//successful response
}
}, function errorCallback(response) {
//error
}
)
};
解决方案
您可以使用函数句柄来执行函数。这将是对函数的引用:
//existing functions
function one() { console.log("one") };
function two() { console.log("two") };
function three() { console.log("three") };
//function that will execute other functions
function exec(number) {
//we will assign a function here
let toExecute;
//simple condition to choose the function to execute at the end
if (number == 1) {
toExecute = one;
} else if (number == 2) {
toExecute = two;
} else if (number == 3) {
toExecute = three;
}
//adding () executes whatever function is assigned to the variable
toExecute();
}
exec(3);
exec(2);
exec(1);
推荐阅读
- .net - 如何调查不同地区的 Azure Function 冷启动较慢?
- php - 多维阵列到单个
- ios - 由于 Xcode 错误,无法在 WebStorm 中调试 React Native
- sockets - 期望使用套接字向后台作业发送密码
- javascript - TinyMCE 上传图片:JSON 输入意外结束
- python - 从时间戳列表中获取小时和分钟
- ubuntu - 在操作系统中分配 CPU 到进程意味着什么?
- vue.js - Nuxt 生成不清除缓存以获取新更新
- postgresql - brin 索引可以在两列上使用吗?
- machine-learning - Clarifai 的特点