0

I use class syntax for the definition of several prototypes. At a certain point in my code I have to create a new object but which object exactly depends on the prototype name which is stored as a string in a variable.

In Calling a JavaScript function named in a variable there is a solution to call a function when its name is stored in variable without using eval(). How can I achieve the same thing for creating an object from a prototype like this parser = new VARIABLE_CONTAINING_PROTOTYPENAME?

Community
  • 1
  • 1
Cutú Chiqueño
  • 855
  • 1
  • 10
  • 24

1 Answers1

2

Not sure I'm a huge fan of using strings to represent types, but I don't know your use case, so I won't judge!

To new a prototype based on a string, you're probably best off creating a factory function:

function factory(name) {
    switch (name) {
        case "Object":
            return new Object();
        case "Array":
            return new Array();
        default:
            return null;
    }
}

var myObj = factory("Object");

Alternatively, you could create an object and then index into it to get the constructor:

var constructors = {
    "Object": Object,
    "Array": Array
};

var myObj = new constructors["Object"];
Joe Clay
  • 33,401
  • 4
  • 85
  • 85
  • I must admit that I do not like this approach either though I am not so experienced to think of another approach. The use case goes like this: I have HTML elements on the website that are classified by `data-evnt-type` attribute. When the page is loaded the javascript looks for each element with such an attribute and adds an eventListener to it. When the event is triggered a parser object is created but which parser object depends on the value in the `data-evnt-type` attribute that holds part of the parsers name. Actually the second solution is what I was looking for within this approach – Cutú Chiqueño Dec 06 '16 at 15:54
  • @CutúChiqueño: Eh, it's not the hackiest thing I've ever seen, and I can't think of a better approach off the top of my head! – Joe Clay Dec 06 '16 at 15:58