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,
}
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,
}
Share
Improve this question
edited Nov 7, 2012 at 15:59
mrk
5,1273 gold badges28 silver badges42 bronze badges
asked Nov 7, 2012 at 15:57
Kermit the FrogKermit the Frog
3,9697 gold badges34 silver badges39 bronze badges
1
- since classes are just functions, this is a duplicate of How to execute a JavaScript function when I have its name as a string – jbabey Commented Nov 7, 2012 at 16:07
4 Answers
Reset to default 7Technically, 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 plicated, but still the same general idea.
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.
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);
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]