4

I have xml file like this

<X/>

I want to be able to construct JavaScript object from it. I have to retrieve JavaScript object from tag. Possibly with Reflection API. For simplicity tag name equals to class name.

How can I retrieve class from it's string name?

<html>
    <head>
        <script type="text/javascript">
                class X {
                    work(number, text, check) {
                        console.log("X.work: " + number + ", " + text + ", " + check);
                    }
                }
                // 1)
                var x1 = new X();
                x1.work(1, "Hello", false);
                // 2)
                var className = "X";
                var klass = window[className];
                var x2 = new klass();
                x2.work(1, "Hello", false); // klass == undefined
        </script>
    </head>
</html>

I have following input there for Chrome 51.0.2704.103

 X.work: 1, Hello, false
 Uncaught TypeError: Cannot read property 'work' of undefined

Can I work with class in JavaScript just knowing it name?

cweiske
  • 30,033
  • 14
  • 133
  • 194
Dmitry Kolesnikovich
  • 669
  • 2
  • 15
  • 33

2 Answers2

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: class X { ... },
    Y: class Y { ... }
};

// or:

class X { ... }

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

// then:

new nodes['X'](...);
deceze
  • 510,633
  • 85
  • 743
  • 889
0

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);
Dmitry Kolesnikovich
  • 669
  • 2
  • 15
  • 33