Create instance of “Class” Using “Reflection” in J

2020-04-08 11:25发布

I searched the web for some way to create instance of "Class" in "reflection" using javaScript but I found nothing.

generally i'm trying to do someting like java code.

Object o = Class.forename("MyClassName");

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?

Thankes.

标签: javascript
3条回答
Luminary・发光体
2楼-- · 2020-04-08 12:08

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

The above only works if MyClassName is in the global scope.

查看更多
够拽才男人
3楼-- · 2020-04-08 12:14

Classes in Javascript are nothing but global functions. So you should be able to do this:

var o = new window["MyClassName"];

for example:

var o = new window["Array"];

Keep in mind that this example is just an example. Arrays should be created via [] syntax.

查看更多
太酷不给撩
4楼-- · 2020-04-08 12:26

This is working for me:

var obj = eval("new  " + className + "()");
查看更多
登录 后发表回答