0

I have an array with names of constructors var arr = ['Class1', 'Class2', 'Class3'].

function Class1() {
     this.name = 'class1';
}

Is it possible to dynamically create instances of these classes? I mean something like

var class1Object = new arr[0]();

I tried that but it isn't working (Uncaught TypeError: string is not a function).

dKab
  • 2,658
  • 5
  • 20
  • 35

2 Answers2

2

functions defined in "global" scope are actually created on the window object, so you can do this (as long as the code is in the head of the page, and not scoped to something specific):

function Class1(){
    this.name = 'class1';
}

var className = "Class1";
var c1 = new window[className]();

Live example: http://jsfiddle.net/vdf4W/

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Previously answered in this post (Google: Dynamic Instantiation In JavaScript)

Dynamic Instantiation In JavaScript

Community
  • 1
  • 1
Jeff
  • 1