Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass in a class name as variable using javascript

Tags:

javascript

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,

}
like image 652
Kermit the Frog Avatar asked Nov 07 '12 15:11

Kermit the Frog


People also ask

Can we use class name as variable?

Answer : Yes we can have it.

How do you declare a class variable in JavaScript?

To declare a variable within a class, it needs to be a property of the class or, as you did so, scoped within a method in the class. It's all about scoping and variables are not supported in the scope definition of a class.

Can we use name as variable in JavaScript?

The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter. Names can also begin with $ and _ (but we will not use it in this tutorial).

Can you pass this as a parameter in JavaScript?

"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.


1 Answers

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.

like image 156
Matt Greer Avatar answered Oct 16 '22 23:10

Matt Greer