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,
}
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:
If your function is actually defined at say
my.namespace.Person, then it’s a bit more complicated, but still the same general idea.