3

Possible Duplicate:
Create instance of “Class” Using “Reflection” in JavaScript

Java has Class.forName("XYZClass") to load class at run time. Is there any alternate for Class.forName("XYZClass") in JavaScript?

Community
  • 1
  • 1
gmuhammad
  • 1,434
  • 4
  • 25
  • 39

1 Answers1

2

Personally I think you are trying to literally translate Java code to JavaScript rather than using idiomatic constructs (well, Class.forName() isn't idiomatic in Java as well). However, let's give it a try:

function XYZClass() {
    this.answer = 42;
}

This is your class. Normally you would create it using:

var xyz = new XYZClass();

With "reflection" in JavaScript this works:

var className = "XYZClass";
var xyz = new window[className]();
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I did not understand your code properly, and I am getting error "TypeError: window[className] is not a constructor". – gmuhammad Mar 13 '12 at 08:35
  • 1
    @gmuhammad: and does `new window.XYZClass()` work? Also look at: http://stackoverflow.com/questions/9462881, it has a similar solution. – Tomasz Nurkiewicz Mar 13 '12 at 08:39
  • I got your point now, at first try XYZClass was not declared as global. Now I declared it as global and it's working now. And Now I got it why it's working, it's accessing class/function using window which is top level global variable. Thanx. :) – gmuhammad Mar 13 '12 at 08:48