Dynamically create a class using a variable

How can I instantiate a class by specifying a variable name? Consider this method inside the class:

animate: function(el, build) { 
        console.log(build.effect); 
        var animationClass = new build.effect(el,build); 
}, 

An assembly is an object that contains a lot of material, but, most importantly, an “Effect”. This effect is the name of an independent animation class - one called "MarioKartMenu".

console.log (build.effect) displays "MarioKartMenu". But of course I get: TypeError: The result of the expression 'build.effect' [MarioKartMenu] is not a constructor.

If I destroy dynamism and just make the code as such:

animate: function(el, build) {
        var animationClass = new MarioKartMenu(el,build);
    }, 

It works great. Is it possible to make it dynamic, as I try to do?

+5
source share
3 answers

MarioKartMenu , , :

window["MarioKartMenu"]

, window.

, , , :

var menuConstructor = window[build.effect];
var animationClass = new menuConstructor(el, build);
+5

build.effect ( , ), :

animate = function(el, build) {
    var animationClass = new build.effect(el,build);
}
// ...

b = ...;
b.effect = MarioKartMenu;
animate(e, b);
+2

- JavaScript eval(), , . (Soemthing : var animationClass = eval("new "+build.effect+"(el, build)");, , , eval(), .). - .

My second thought is that MarioKartMenuit is not appropriately abstracted. Thus, I would build a simple class around it that takes the effect name as the third parameter and uses the operator switch()to select among all available effects, creates the correct value and returns it.

0
source