0

You can use bracket notation to fetch an object:

var items = {};
items.obj1 = {};

var type = 'obj1';
var myFunc = function(type){
    var newObj = items[type]; //returns items.obj1
};

How can you do the same to dynamically create an object using constructor functions?

var Constructor1 = function() {};
var Constructor2 = function() {};

var type = 'Constructor2';
var myFunc = function(type){
   var newObj = new type(); // how do you invoke either constructor?
};
Data
  • 1,277
  • 10
  • 17

1 Answers1

1

In your example, try the following:

var myFunc = function(type) {
  return new window[type]();
}
flamingcow
  • 341
  • 2
  • 7