创建& quot; Class& quot;的实例使用& quot;反射&"在JavaScript中 [英] Create instance of "Class" Using "Reflection" in JavaScript
问题描述
我在网上搜索了一些使用javaScript在反射"中创建类"实例的方法,但是我什么都没找到.
I searched the web for some way to create instance of "Class" in "reflection" using javaScript but I found nothing.
通常,我试图做一些类似Java代码的事情.
generally i'm trying to do someting like java code.
Object o = Class.forename("MyClassName");
但是在javaScript中,以这样的方式,当我只有类的名称时,我将得到类的实例,知道吗?
but in javaScript, in such way that I'll get the instance of class when I have only the name of the class, any idea?
谢谢.
推荐答案
JavaScript没有类.但是,如果使用类",则表示您具有构造函数:
JavaScript doesn't have classes. But if by "class" you mean you have a constructor function:
function MyClassName() {
// do constructor things here
}
但是该函数的名称在变量中:
But the name of that function is in a variable:
var someclass = "MyClassName";
然后,您可以像这样实例化一个实例:
Then you can instantiate an instance like this:
var obj = new window[someclass]();
仅当 MyClassName
在全局范围内时,以上内容才有效.
The above only works if MyClassName
is in the global scope.
这篇关于创建& quot; Class& quot;的实例使用& quot;反射&"在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!