0

Can anyone tell me what I can replace the evil eval with in this code?

var x = function(funcName) {
    function funcA () {
        console.log("a");
    }
    
    function funcB () {
        console.log("b");
    }   
    
    var funcToRun = eval(funcName);
    return funcToRun();
};

x("funcA");
x("funcB");

I've see a bunch of different solutions, but none seem to fit this scenario. Essentially, I need to be able to pass a string into a function as a "config" of which sub-function to run. I don't have access to the code that calls x, I've just been instructed that only primitive and string values can be configured in the call.

P.S. This is a super simplified version of the actual function.

Thanks! James

Jimi
  • 13
  • 5
  • `const fns = { funcA() { ... }, funcB() { ... } }; fns[funcName]()`… – deceze Aug 13 '20 at 09:58
  • Thanks deceze, but that only works from outside the function. I need to be able to reference the sub-functions from within the primary function. – Jimi Aug 13 '20 at 11:18
  • Why would that only work "from outside the function"?! – deceze Aug 13 '20 at 11:21
  • You're referencing the properties/functions of fns from outside of the function. The question indicated I need to reference the properties/functions of fns from within the function. If I'm not understanding, please show me an example where you call funcA or funcB by string name from with the fns braces/scope? The string passed into the fns function wouldn't be available to the outer scope to reference. – Jimi Aug 14 '20 at 14:28
  • You very much seem to be misunderstanding. Put my above example as the contents of your `var x = function (funcName) { ... }` function body. Instead of declaring `function funcA` and `funcB` as *you* are doing, do it as I'm showing, as an object. It's basically what's happening in the accepted answer too. – deceze Aug 14 '20 at 15:02
  • Thanks deceze, I see what you're saying now. It wouldn't suit my purposes, as executing the sub-function isn't the only thing I need to do when making the call, but I do see that your suggestion would answer the question as stated, thank you. – Jimi Aug 17 '20 at 10:03

1 Answers1

0

You could just create an object and add those functions as properties that you can then access with a string.

var x = function(funcName) {
  function funcA() {
    console.log("a");
  }

  function funcB() {
    console.log("b");
  }

  const fs = {
    funcA,
    funcB
  }

  var funcToRun = fs[funcName]
  return funcToRun();
};

x("funcA");
x("funcB");
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Thanks Nenad. Seems so simple now :D. I'm still interested to know if there is some way to directly reference those functions without having to wrap them in their own object, but your answer solves my question. – Jimi Aug 13 '20 at 11:28