Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中使用“反射”创建“类”的实例(Create instance of “Class” Using “Reflection” in JavaScript)

I searched the web for some way to create instance of "Class" in "reflection" using javaScript but I found nothing.(我在网上搜索了一些使用javaScript在“反射”中创建“类”实例的方法,但没有发现任何结果。)

generally i'm trying to do someting like java code.(通常我想做一些类似Java代码的事情。)

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?(但是在javaScript中,以这样的方式,当我只有类的名称时,我将获得类的实例,知道吗?)

Thankes.(谢谢)

  ask by Asaf Maimon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScript doesn't have classes.(JavaScript没有类。)

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.(仅当MyClassName在全局范围内时,以上方法才有效。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...