8

How can I pass in a class name as a variable using javascript?

Let's say I have the class Person.

I want to pass in the name of the class to a function so that that function can call that class.

so the function is

function openClass(name)

I want to pass in

openClass('person')

so that openClass can call the class person

for example

function openClass(name)
{
    return new name() // here I want this line to actually 
                      // call the class "Person" if that is 
                      // what is passed in as a name parameter,

}
mrk
  • 4,999
  • 3
  • 27
  • 42
Kermit the Frog
  • 3,949
  • 7
  • 31
  • 39
  • since classes are just functions, this is a duplicate of [How to execute a JavaScript function when I have its name as a string](http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) – jbabey Nov 07 '12 at 16:07

4 Answers4

7

Technically, there are no classes in JavaScript. Although many third party libraries do create a class system on top of JavaScript.

The "class" is typically a constructor function. So if you have the name of the function, it's a matter of digging it out of the global scope. Assuming the function is defined globally:

var Constructor = window[name];
return new Constructor();

If your function is actually defined at say my.namespace.Person, then it's a bit more complicated, but still the same general idea.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
3

You can do

function openClass(name) {
    return new window[name]();
}

Demonstration (open the console)

Of course, if you don't declare your class as a global function but in a specific object or array, just replace window by this object or array.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

You can just pass the constructor of that class. So if the class is Person, it will have a constructor

var Person = function(){
    //...
}

you can pass that in to getClass as an argument

var getClass = function(constructor){
    return new constructor()
};

var newObject = getClass(Person);
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
-3

Simply call openClass(Person).

That passes the Person function into openClass, where it can be called normally.

If you really need to pass it as a string, then you can look for the Person function by name:

window[name]
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • 3
    Oh, that's curious, all the responses had one downvote except this one...you need to do that with 12.7k reputation? – Vithozor Nov 07 '12 at 16:02