0

Global functions can be accessed by their names as in:

        x = function () {
            alert(1);
        }
        window['x']();

This will execute the function. But when I have something like this:

        function outer() {
           var inner = function() {

                   }
           window['inner'](); //This will not execute as inner is not global.
        }

Is there any way to get around this? Application: I am trying to avoid using a switch statement where the action for each case is merely to execute a specific function based upon the value of the string. Having these functions named based upon the potential string value, entire switch statements are reduced to one statement. Example:

           switch (someString) {
             case 'value1' : myValue1Func();
                             break;
             case 'value2' : myValue2Func();
                             break;
              ...
            }

Can be condensed into one:

         window ["my" + someString + "Func"]();

But this will only work for global functions. I do not want to make local functions global just to do this.

Sunny
  • 9,245
  • 10
  • 49
  • 79
  • 2
    The answer is no. In your case, `inner` is declared without `let` or `var` so it actually *would* be global. Generally any situation that leads a person to ask a question like this is an indication of some upstream design mistake. – Pointy Jul 19 '20 at 21:41
  • @Pointy that missing var or let was a typo. I corrected it. – Sunny Jul 19 '20 at 21:42
  • 2
    `{ value1: myValue1Func, ... }[someString]()` – Jonas Wilms Jul 19 '20 at 21:45
  • @JonasWilms You are still maintaining a mapping which is effectively a simplified switch statement anyway albeit a better approach than the switch. – Sunny Jul 19 '20 at 21:53
  • 1
    @Sunny how is `var inner = function() {} window['inner']();` any different to a map? You still need to create the functions and name them accordingly. If "maintaining a mapping" is the actual issue, then I'm afraid you wont get around it. – Olian04 Jul 19 '20 at 22:32
  • @Olian04 You and Jonas are right. I cannot get around this issue other than making the functions global or maintaining a "mapping" in some form. If the functions are global, the mapping is not required. – Sunny Jul 19 '20 at 23:05
  • @Sunny making them global and accessing them through the window object, is the exact same thing as what Jones suggested, it's just using slightly different syntax. – Olian04 Jul 19 '20 at 23:08
  • @Olian04 OK. I get it. Thanks – Sunny Jul 19 '20 at 23:10

0 Answers0