0

Can I dynamically call a static function with name as a string? After some try it's all i can get :

   class Test{
        static Instance(){
          console.log( "Instantiated" );
        };
    };

    Test.Instance();//<-- ok

    var testVar = "Test";

    eval( testVar + ".Instance()" ); // ok but eval is evil!

    window[testVar].Instance();//<-- undefined is not an object (evaluating 'window[testVar].Instance')
Giuseppe Canale
  • 470
  • 7
  • 15

1 Answers1

3

You could use new Function

Stack snippet

class Test {
  static Instance() {
    console.log("Instantiated");
  };
};

var testVar = "Test";

var func = function(string) {
  return (new Function('return (' + string + ').Instance()')());
}

func(testVar);

Here is some reading regarding new Function compared with eval

Asons
  • 84,923
  • 12
  • 110
  • 165
  • That won't work unless `Test` is a global variable, which according to the question, it isn't. –  May 07 '18 at 17:58
  • ...also, `new Function(...)()` will suffer from *almost* all the same security concerns as `eval`. –  May 07 '18 at 18:01
  • @CrazyTrain How is OP's own `window[testVar].Instance();` say it is _not_ a global variable? And the dupe linked suggests `eval` and _objectify_ it as solutions, and with that in mind, you still think this can't count as an option as well? – Asons May 07 '18 at 18:10
  • @CrazyTrain Btw, should I assume you also down voted? – Asons May 07 '18 at 18:10
  • @LGSon, thanks a lot! – Giuseppe Canale May 07 '18 at 18:29
  • @LGSon: `//<-- undefined is not an object (evaluating 'window[testVar].Instance')` If `Test` was global, there would be no error. –  May 07 '18 at 18:42
  • ...and if `Test` *is* global, then there's no need to use `Function` or `eval`. –  May 07 '18 at 18:43
  • Oh, you're right. Because `class` syntax creates a global that does not add to the `window` object. Boy I sure hate how inconsistent they've made the global object. –  May 07 '18 at 18:46
  • LGSon: Yep, sorry about that. Though @GiuseppeCanale should be aware of the security issues. While it's true that `Function` eval'd code can't access local variables, just globals, it's still evaluating the code, so if the string is insecure, the same threats as `eval` do exist. Putting the classes on an object will avoid the need for runtime dynamic code evaluation. –  May 07 '18 at 18:52
  • @CrazyTrain Agree with that, and both the link I provided along with the dupe serves that purpose. – Asons May 07 '18 at 19:10