Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a Class dynamically via variable

How can I instantiate a class by throwing in a variable name? Consider this method inside a class:

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

Build is an object containing lots of stuff, but most importantly an "effect". This effect is the name of an independent animation class-- one is called "MarioKartMenu".

console.log(build.effect) prints out "MarioKartMenu". But of course I get: TypeError: Result of expression 'build.effect' [MarioKartMenu] is not a constructor.

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

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

It works just fine. Is it possible to make it dynamic like I'm attempting to do?

like image 281
Ryan Florence Avatar asked May 28 '09 22:05

Ryan Florence


2 Answers

If the function MarioKartMenu is defined in the global scope, you can access it by its string name using:

window["MarioKartMenu"]

This works because all global variables are properties of the window object.

Given the above, you can implement what you want by using:

var menuConstructor = window[build.effect];
var animationClass = new menuConstructor(el, build);
like image 95
Ayman Hourieh Avatar answered Nov 01 '22 10:11

Ayman Hourieh


Just assign the constructor to build.effect (not a string containing its name) and it should work:

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

b = ...;
b.effect = MarioKartMenu;
animate(e, b);
like image 22
sth Avatar answered Nov 01 '22 11:11

sth