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,

}
1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also assuming window is the global object. It isn't always (say in node.js for example)
People seem to be downvoting this approach (see dystroy's answer too), curious why
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.

Comments

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

Comments

-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]

1 Comment

Oh, that's curious, all the responses had one downvote except this one...you need to do that with 12.7k reputation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.