0

Is there a way load class names as variables? new window[a] does not seem to work. I'm getting an error of TypeError: window[a] is not a constructor.

require([
    'myController'
], function (myController) {
    // this is working fine
    // new myController().init();

    $(function() {
        var a = $('.test').attr('class'); // this returns myController
        new window[a]; // error here
    });
});
basagabi
  • 4,900
  • 6
  • 38
  • 84

1 Answers1

-1

To do what you want you would need to use eval like this:

eval("new " + window[a] + "()");

Working example: https://jsfiddle.net/ybjo4pn9/


NOTE: Use eval with caution.

Community
  • 1
  • 1
mikhail
  • 5,019
  • 2
  • 34
  • 47
  • 1
    Perhaps it was that using eval() is dangerous. But sometimes it's the best way to solve a problem. There's a lengthy discussion here: "When is JavaScript's eval() not evil?" -- http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – Eric Bronnimann Feb 16 '16 at 17:48
  • That's the only reason I can think of. But I gave an unbiased answer for how to solve this particular problem without major architectural changes. I would never actually use this in my own code. – mikhail Feb 16 '16 at 18:03