首页 > 解决方案 > 如何避免使用 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
        }
    )
};

标签: javascriptangularjs

解决方案


您可以使用函数句柄来执行函数。这将是对函数的引用:

//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);


推荐阅读