Skip to content Skip to sidebar Skip to footer

In Javascript How Can I Retrieve Class From It's String Name?

I have xml file like this I want to be able to construct JavaScript object from it. I have to retrieve JavaScript object from tag. Possibly with Reflection API. For sim

Solution 1:

Since "classes" in Javascript are nothing but regular variables/functions, what you're really asking for is "variable variables", which is most easily realised using an object mapping:

var nodes = {
    X: classX { ... },
    Y: classY { ... }
};

// or:classX { ... }

var nodes = { X: X };
// or the convenience shorthand in ES6:var nodes = { X };

// then:new nodes['X'](...);

Solution 2:

There is eval keyword that works in my Chrome 51.0.2704.103. No need to make global map of classes.

var className = "X";
var klass = eval(className);
var x2 = new klass;
x2.work(1, "Hello", false);

Post a Comment for "In Javascript How Can I Retrieve Class From It's String Name?"