如何使用javascript将类名作为变量传入

Ker*_*rog 7 javascript

如何使用javascript将类名作为变量传入?

假设我有班级人物.

我想将类的名称传递给一个函数,以便该函数可以调用该类.

所以功能是

function openClass(name)
Run Code Online (Sandbox Code Playgroud)

我想传入

openClass('person')
Run Code Online (Sandbox Code Playgroud)

这样openClass就可以调用类人

例如

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,

}
Run Code Online (Sandbox Code Playgroud)

Mat*_*eer 7

从技术上讲,JavaScript中没有类.虽然许多第三方库确实在JavaScript之上创建了一个类系统.

"类"通常是构造函数.因此,如果您拥有该功能的名称,则需要将其从全局范围中挖掘出来.假设函数是全局定义的:

var Constructor = window[name];
return new Constructor();
Run Code Online (Sandbox Code Playgroud)

如果你的函数实际上是定义的my.namespace.Person,那么它有点复杂,但仍然是相同的一般想法.