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?

5
  • Can we have some context of why you would ever want to do this? Commented Jun 23, 2016 at 11:46
  • I have xml file where my tag names are class names. So by reflection I want to construct JavaScript object from it's xml description. Commented Jun 23, 2016 at 11:49
  • For me it looks like a chrome bug. I think you should be able to access X by window.X Commented Jun 23, 2016 at 15:00
  • Or maybe not, things get different when implicit strict mode gets in place Commented Jun 23, 2016 at 15:01
  • for me typeof window.X == "string" in Chrome Commented Jun 23, 2016 at 15:08

2 Answers 2

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'](...);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.